Iai*_*oat 0 c# generics reflection
我正在使用.Net framework 2.0来尝试执行以下操作:
我有一个返回int列表的外部服务.反过来,我使用每个int来查找具有属性的相应Type,其中包含属性key; 该属性的值与搜索参数匹配.
使用Type tI想调用泛型方法,但我无法做到这一点.因为我只会在运行时知道Type,我怀疑我可能不得不使用反射来调用泛型方法GetResultsForType- 这是正确的方法吗?
[MyAttribute(key1 = 1)]
class A{
//some properties
}
[MyAttribute(key1 = 2)]
class B{
//some properties
}
//and so on (for hundreds of classes). The key is unique for every class.
public class Foo{
public void DoSomething(){
IList<int> keys = QuerySomeExternalService();
Assembly asm = LoadAssemblyFromSomewhere();
Type[] types = asm.GetTypes();
foreach(int key in keys){
Type t = SearchTypesForAttributeWithMatchingKey(types, key); //I omitted caching of all the keys and Types into a Dictionary on first iteration for brevity.
IList<t> results = GetResultsForType<t>(); //won't work!
//do something with the results
}
}
Type SearchTypesForAttributeWithMatchingKey(Type[] types, int key){
foreach(Type t in types){
object[] attributes = t.GetCustomAttributes(typeof(MyAttribute),false);
MyAttribute myAtt = attributes[0] as MyAttribute;
if(myAtt.Key == key) return t;
}
}
IList<T> GetResultsForType<T>(){
IList<T> results = new List<T>();
bool querySuccess = true;
while(querySuccess){
T result;
querySuccess = QueryExternalService<T>(out result);
results.Add(result);
}
return results;
}
}
Run Code Online (Sandbox Code Playgroud)
是的,您必须使用反射来使用System.Type而不是通用参数化来调用泛型方法.MakeGenericMethod(params Type[])找到泛型方法后,可以在methodInfo上使用该方法.
如果您知道该方法经常被调用但具有少量类型,则可以缓存委托以调用正确的版本.
就像是::
typeof(Foo).GetMethod("YourMethod").MakeGenericMethod(type).Invoke(new[]{parameters});
Run Code Online (Sandbox Code Playgroud)