【发布时间】:2011-01-11 19:28:40
【问题描述】:
我正在使用 .Net framework 2.0 来尝试执行以下操作:
我有一个返回 int 列表的外部服务。反过来,我使用每个 int 来找到一个对应的 Type,它有一个带有属性 key 的 Attribute;该属性的值与搜索参数匹配。
使用类型t 我想调用一个泛型方法,但我不能这样做。由于我只会在运行时知道类型,我怀疑我可能必须使用反射来调用泛型方法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;
}
}
【问题讨论】:
-
这与您的上一个问题 (stackoverflow.com/questions/4661211/…) 非常相似,您使用
System.Type的实例代替类型参数来调用通用方法。我知道您并没有真正寻求架构方面的建议,但是如果您必须左右与类型系统作斗争,则表明您的设计有问题。我个人很想知道您在这里实际尝试解决什么样的问题,而不是如何您尝试解决它,也许有人可以提出更清洁的方法。跨度>
标签: c# generics reflection