我有一个方法如何基于字典中的映射动态地调用泛型方法?
String Foo<T> where T: WebControl
现在我有像“超链接”的字符串。基于从字符串到泛型的映射,需要调用Foo<Hyperlink>
。
字典如何看起来像?
它不是:
private Dictionary<string, Type> _mapping = new Dictionary<string, Type>()
{
{"hyperlink", typeof(HyperLink)}
};
我要访问它像Foo<_mapping[mystring]>
这可能吗?如果是的话,字典应该如何?
编辑:接受的解决方案
String _typename = "hyperlink";
MethodInfo _mi = typeof(ParserBase).GetMethod("Foo");
Type _type = _mapping[_typename];
MethodInfo _mig = _mi.MakeGenericMethod(_type);
return (String)_mig.Invoke(this, new object[] { _props }); // where _props is a dictionary defined elsewhere
// note that the first parameter for invoke is "this", due to my method Foo is not static
我编辑了我的文章。我明白了你现在想要实现的目标。你想动态地调用一个通用函数。 – Thomas 2010-03-06 00:45:13
无论如何。我根据你的描述编辑了标题,我正在尝试做什么=) – citronas 2010-03-06 00:49:57