我有一个类
公共类A< T> {公共静态字符串B(牛逼OBJ) {返回TransformThisObjectToAString(OBJ); } }
使用String以上纯属示范性。我可以这样调用静态函数就好上的已知/指定类型:
字符串s = A< KnownType> .B (objectOfKnownType);
如何让我这个电话,如果我不知道的 T 事前,而我有型的类型持有该类型的变量。如果我这样做:
键入T = typeof运算(字符串); 字符串s = A< T> .B(someStringObject);
我得到这个编译器错误:
无法隐式转换类型'T'到'对象'解决方案
您不能。泛型类型标识符已在编译时是已知的。
修改
作为其他职位,这似乎被动态地生成方法,并调用它是可能的 - 这当然有危险。见托马斯的大坍帖子更多inforation。
I have a class
public class A<T> { public static string B(T obj) { return TransformThisObjectToAString(obj); } }The use of string above is purely exemplary. I can call the static function like this just fine on a known/specified type:
string s= A<KnownType>.B(objectOfKnownType);How do I make this call, if I don't know T beforehand, rather I have a variable of type Type that holds the type. If I do this:
Type t= typeof(string); string s= A<t>.B(someStringObject);I get this compiler error:
Cannot implicitly convert type 't' to 'object'解决方案
You can't. Generic type identifiers have to be known at compile time.
edit
as of other posts, it appears to be possible by dynamicly generating the method and invoking it - which has dangers of course. See Thomas' and Dathan's posts for more inforation.
更多推荐
设置在运行时泛型类型
发布评论