C#将泛型方法与类型一起使用 [英] C# using generic method with Type
问题描述
我正在使用.Net Framework 2.0尝试执行以下操作:
I'm using .Net framework 2.0 to try and do the following:
我有一个外部服务,它返回一个int列表.反过来,我使用每个int来找到一个对应的Type,该Type具有带属性的属性key.该属性的值与搜索参数匹配.
I've an external service which returns a list of int. In turn I use each int to find a corresponding Type which has an Attribute with a property, key; the value of that property matches the search parameter.
使用类型t
我想调用泛型方法,但是我无法做到这一点.因为我只会在运行时知道Type,所以我怀疑我可能必须使用反射来调用通用方法GetResultsForType
-这是解决此问题的正确方法吗?
Using the Type t
I'd like to call a generic method, but I'm unable to do this. As I will only know the Type at runtime, I suspect I may have to use reflection to invoke the generic method GetResultsForType
- is this the correct way to go about this?
[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;
}
}
推荐答案
是的,您必须使用反射来使用System.Type
而不是泛型参数化来调用泛型方法.找到通用方法后,可以在methodInfo MakeGenericMethod(params Type[])
上使用该方法.
Yes you have to use reflection to call a generic method using a System.Type
rather than a generic parameterization. You can use the method on methodInfo MakeGenericMethod(params Type[])
after finding the generic method.
如果您知道该方法经常被调用但类型很少,则可以缓存委托以调用正确的版本.
If you know the method is called often but with a small number of types, you can cache delegates to invoke the right version.
类似的东西:
typeof(Foo).GetMethod("YourMethod").MakeGenericMethod(type).Invoke(new[]{parameters});
这篇关于C#将泛型方法与类型一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!