简体   繁体   English

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

[英]Is there a way to find an interface implementation based on a generic type argument?

I have a data access library that has a few classes that all implement the same interface, which has a generic type parameter: 我有一个数据访问库,其中包含一些都实现相同接口的类,该类具有通用类型参数:

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 

Rather than forcing consumers of this library to instantiate one of the four repository classes separately for each <TEntity> , I am hoping that there's some way that I can create a static method in a "helper/utility" class in the same assembly that will be able to discern which implementation to instantiate, create an instance, and execute the GetByCommonStringColumn method. 我希望不是让该库的使用者为每个<TEntity>分别实例化四个存储库类之一,而是希望可以通过某种方式在同一程序集中的“ helper / utility”类中创建静态方法,该方法将能够识别要实例化的实现,创建实例并执行GetByCommonStringColumn方法。 Something like... 就像是...

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;
}

Is anything like this possible? 这样有可能吗?

That example still needs further fixing.. For each repository it is missing a constraint. 该示例仍需要进一步解决。对于每个存储库,它都缺少约束。 For each public (right now it is invalid private) method it is also missing a functional body.. For that interface method it requires a generic argument. 对于每个公共方法(现在它是无效的私有方法),它也缺少功能体。对于该接口方法,它需要一个泛型参数。

Then try, or play around, if I understood you right: 如果我理解正确,然后尝试或玩一下:

 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; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM