2010-03-06 74 views
0

我有一个方法如何基于字典中的映射动态地调用泛型方法?

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 
+0

我编辑了我的文章。我明白了你现在想要实现的目标。你想动态地调用一个通用函数。 – Thomas 2010-03-06 00:45:13

+0

无论如何。我根据你的描述编辑了标题,我正在尝试做什么=) – citronas 2010-03-06 00:49:57

回答

1

你想要什么是不可能的,因为这将是运行时(例如字典以后可以包含任何内容)。

如果你想通过运行时手工生成它,你可以这样做,但是你不会得到编译时检查C#对泛型的检查。你可以通过MethodInfo.MakeGenericMethod来这个。

像这样:

var m = typeof(MyClass); 
var mi = ex.GetMethod("Foo"); 
var mig = mi.MakeGenericMethod(_mapping["hyperlink"]); 

//Invoke it 
mig .Invoke(null, args); 
+0

那好吧,我该如何通过运行时生成它?我手动填写这个字典,所以我知道哪个类派生自WebControl。 – citronas 2010-03-06 00:29:01

+0

@citronas - 我提供了一个通用方法的简单示例,如果您需要名为MakeGenericType的类,则有一个等效方法:http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx – 2010-03-06 00:31:59

+0

非常感谢,我能够根据您的示例找到解决方案,尽管我几乎没有选择Relection的经验=)我简化了解决方案并将其编辑到我的问题中,以便其他人可以从此线程中受益。 – citronas 2010-03-06 00:46:55

1

这种方式是不可能的。泛型只支持编译 - 划分绑定。

1

不,你不能那样做。你的泛型类型希望在编译时创建它自己,但它不知道运行时的类型。但是,您可以使用反射。

Type untypedGeneric = typeof(Foo<>); 
Type typedGeneric = untypedGeneric.MakeGenericType(_mapping[mystring]); 
相关问题