簡體   English   中英

有沒有一種方法可以基於泛型類型參數找到接口實現?

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

我有一個數據訪問庫,其中包含一些都實現相同接口的類,該類具有通用類型參數:

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

這樣有可能嗎?

該示例仍需要進一步解決。對於每個存儲庫,它都缺少約束。 對於每個公共方法(現在它是無效的私有方法),它也缺少功能體。對於該接口方法,它需要一個泛型參數。

如果我理解正確,然后嘗試或玩一下:

 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