设置在运行时泛型类型

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

我有一个类

公共类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.

更多推荐

设置在运行时泛型类型

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

发布评论

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

>www.elefans.com

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