在运行时设置泛型类型

编程入门 行业动态 更新时间:2024-10-22 22:49:17
本文介绍了在运行时设置泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一堂课

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.

更多推荐

在运行时设置泛型类型

本文发布于:2023-06-10 22:53:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/620809.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!