C#与泛型的反思

时间:2014-11-11 05:10:14

标签: c# generics reflection

我一直在寻找这个,但没有得到任何地方。我想做以下事情:

在运行时给出类型说Dictionary<string,MyClass>并说出方法ContainsKey(string) 我希望能够提取出这种方法的“通用签名”。那是我想要的 Boolean Dictionary<TKey,TValue>.ContainsKey(TKey)(而不是Boolean ContainsKey(string)

我知道这可以通过以下方式实现

var untyped_methods = typeof(DictObject).GetGenericTypeDefition().GetMethods();
// and extract the method info corresponding to ContainsKey

但是可以直接从反映的方法中获取此信息 实际类型而不是通用类型?含义我可以获得通用定义 从已获得的方法如下:

var actual_typed_methods = typeof(DictObject).GetMethods()

本质上是可以从上面第二个片段中返回的MethodInfo对象中获取“ 未键入的 ”方法签名(不是通过比较列表和计算)出)

由于

1 个答案:

答案 0 :(得分:0)

编辑:也许这就是您想要的。不确定您是否真的想要Invoke

如果在调用,则为否(见下文)。如果您只想要定义,那么可以使用typeof(Dictionary<,>)来获取原始通用定义。


不幸的是,如果您想要Invoke,请不要。

演示原因:

void Main()
{
    var genericDictionaryType = typeof(Dictionary<,>);
    var method = genericDictionaryType.GetMethod("ContainsKey");
    var dict = new Dictionary<string, string>();

    dict.Add("foo", "bar");
    Console.WriteLine("{0}", method.Invoke(dict, new[] { "foo" }));
}

产生以下错误:

  

无法对ContainsGenericParameters为true的类型或方法执行后期绑定操作。

听起来很简单。只需致电method.MakeGenericMethod(typeof(string));即可获取实际输入的MethodInfo对象。

不幸的是,你不能。

  

Boolean ContainsKey(TKey)不是GenericMethodDefinition。 MakeGenericMethod只能在MethodBase.IsGenericMethodDefinition为true的方法上调用。

原因是因为定义为bool ContainsKey(TKey)而非bool ContainsKey<TKey>(TKey)的方法。

您需要从正确的ContainsKey签名中获取Dictionary<TK,TV>方法才能使用它。

相关问题