在运行时设置泛型类型 [英] Setting generic type at runtime

查看:40
本文介绍了在运行时设置泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课

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);

如果我事先不知道 T,我如何进行这个调用,而是我有一个 Type 类型的变量来保存类型.如果我这样做:

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);

我收到此编译器错误:

Cannot implicitly convert type 't' to 'object'

推荐答案

你不能.必须在编译时知道通用类型标识符.

You can't. Generic type identifiers have to be known at compile time.

编辑

在其他帖子中,似乎可以通过动态生成方法并调用它——这当然有危险.有关详细信息,请参阅 Thomas 和 Dathan 的帖子.

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.

这篇关于在运行时设置泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆