【问题标题】:C# using generic method with Type [duplicate]C#使用带有类型的泛型方法[重复]
【发布时间】: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


【解决方案1】:

是的,您必须使用反射来调用使用 System.Type 的泛型方法,而不是泛型参数化。找到泛型方法后,您可以使用 methodInfo MakeGenericMethod(params Type[]) 上的方法。

如果您知道该方法被频繁调用但类型较少,您可以缓存委托以调用正确的版本。

类似::

typeof(Foo).GetMethod("YourMethod").MakeGenericMethod(type).Invoke(new[]{parameters});

【讨论】:

    猜你喜欢
    • 2019-06-04
    • 2016-03-31
    • 1970-01-01
    • 2019-08-26
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多