[英]How to use reflection to get implementations of a generic interface
object
。 目標
擁有2條這樣存儲的字典:
IRead<int> new Reader()
IRead<string> new Reader()
public interface IRead<T>
{
T Read(bool[] binary);
int Key( T type );
}
public class Reader : IRead<int>, IRead<string>
{
int IRead<int>.Read( byte[] binary )
{
// does stuff
returns 4;
}
public int Key( int type ) { return 43; }
string IRead<string>.Read( byte[] binary )
{
// does stuff
returns "example";
}
public int Key( string type ) { return 61; }
static StreamProcessor( )
{
// Here I want to get the definitions
}
}
請,當您提出問題時,請編寫可編譯的代碼。 它使每個人的生活更加輕松(也許您的答案是因為您編寫的偽代碼是錯誤的?)
無論如何,這將獲得實現IRead<>
所有類型:
var types = GetType().Assembly.GetTypes()
.Select(t => new
{
Type = t,
MatchingInterfaces = t.GetInterfaces()
.Where(i => i.GetGenericTypeDefinition() == typeof(IRead<>))
})
.Where(t => t.MatchingInterfaces.Any())
您返回密鑰的先決條件沒有多大意義。 您找不到IRead<>
所有實例 。 您需要一個實例來給您一個密鑰。
例如,如果您具有以下代碼,則字典的外觀如何:
var readerOne = new Reader();
var readerTwo = new Reader();
哪個實例進入字典?
您可以得到的最接近的是:
我建議將其分解,因為您要嘗試做一些不同的事情-有些事情很清楚,有些不是。
首先,您要獲取實現IReader的類型:
public IEnumerable<Type> GetTypes<TAssignableFrom>()
{
return this.GetType().Assembly.GetTypes()
.Where(type => type.IsAssignableFrom(typeof (TAssignableFrom)));
}
您想對這些類型做什么? 如果要創建每種類型的實例,則它們需要具有無參數的構造函數或其他相同的構造函數,或者您需要使用一些依賴項注入容器。
假設他們將擁有無參數的構造函數。 我們可以將以上內容更新為
public IEnumerable<Type> GetTypes<TAssignableFrom>()
{
return this.GetType().Assembly.GetTypes()
.Where(type => type.IsAssignableFrom(typeof (TAssignableFrom))
&& type.GetConstructor(Type.EmptyTypes) != null
);
}
現在,您可以實例化一堆類型。
從那里開始變得很模糊。 您將如何處理這些類型? 將它們放入字典中並沒有太大用處,因為它們都是不同的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.