代码之家  ›  专栏  ›  技术社区  ›  AJ.

有没有一种方法可以找到基于泛型类型参数的接口实现?

  •  1
  • AJ.  · 技术社区  · 15 年前

    我有一个数据访问库,它有几个类都实现相同的接口,这些类有一个通用类型参数:

    public interface IGetByCommonStringRepository<TEntity>
    {
        TEntity GetByCommonStringColumn(string commonString);
    }
    
    public class Repository1<Entity1> : IGetByCommonStringRepository<Entity1>
    {
        public Entity1 GetByCommonStringColumn(string commonString)
        {
            //do stuff to get the entity
        }
    }
    
    public class Repository2<Entity2> : IGetByCommonStringRepository<Entity2>
    //...and so on 
    

    而不是强迫这个库的使用者为每个库分别实例化四个存储库类中的一个 <TEntity> ,我希望有某种方法可以在同一程序集中的“helper/utility”类中创建静态方法,该方法能够识别要实例化、创建实例和执行 GetByCommonStringColumn 方法。有点像…

    public static TEntity GetEntityByCommonStringColumn(string commonString) where TEntity : class
    {
        IGetByCommonStringRepository<TEntity> repository = 
            DoMagicalReflectionToFindClassImplementingIGetByCommonString(typeof(TEntity));
        //I know that there would have to an Activator.CreateInstance() 
        //or something here as well.
        return repository.GetByCommonStringColumn(commonString) as TEntity;
    }
    

    这样的事有可能吗?

    事先谢谢。

    1 回复  |  直到 15 年前
        1
  •  1
  •   Jacob Mattison    15 年前

    这个例子还需要进一步修正。对于每个存储库,它都缺少一个约束。对于每个public(现在它是无效的private)方法,它还缺少一个函数体。对于该接口方法,它需要一个泛型参数。

    如果我理解你的话,那就试试看,或者四处游玩:

    public static TEntity clr_bloat_reflected_msdn_method<TEntity>(string commonString) where TEntity : class
            {
                Assembly a = Assembly.GetExecutingAssembly();
                foreach (Type t in a.GetTypes())
                    if (!t.IsAbstract && typeof(IGetByCommonStringRepository<TEntity>).IsAssignableFrom(t))
                        return ((IGetByCommonStringRepository<TEntity>)Activator.CreateInstance(t)).GetByCommonStringColumn(commonString);
                return null;
            }