如何创建 Nullable<T>从类型变量?

编程入门 行业动态 更新时间:2024-10-17 07:22:38
本文介绍了如何创建 Nullable<T>从类型变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在处理表达式,我需要一个方法来接收某种类型(目前未知)的对象.像这样:

I'm working with expressions and I need a method which receives an object of some type (currently unknown). Something like this:

public static void Foobar(object Meh) { }

我需要的是让这个方法返回一个 Nullable 版本的 Meh,但是类型 T 来自 Meh.GetType().所以返回结果是 Nullable,其中 MehType 是 Meh 的类型.

What I need to is make this method return a Nullable<T> version of Meh, but the type T is from Meh.GetType(). So the return would be Nullable<MehType>, where MehType is the type of Meh.

有什么想法或建议吗?

谢谢

更新:我需要这个的原因是因为这个例外:

Update: the reason why I needed this is because of this exception:

未为类型System.Nullable`1[System.Int32]"和System.Int32"定义二元运算符 Equal.

return Expression.Equal(leftExpr, rightExpr);

其中 leftExpr 是一个 System.Nullable1[[System.Int32 并且 rightExpr 是一个 System.Int32.

where leftExpr is a System.Nullable1[[System.Int32 and rightExpr is a System.Int32.

推荐答案

如果你在编译时不知道类型,只能用 object 来表达 - 并且尽快你装箱一个可为空的值类型,你最终得到一个空引用,或者一个装箱的不可空值类型.

If you don't know the type at compile time, the only way of expressing it is as object - and as soon as you box a nullable value type, you end up with either a null reference, or a boxed non-nullable value type.

所以这些片段在结果方面完全相同:

So these snippets are exactly equivalent in terms of the results:

int? nullable = 3; object result = nullable; int nonNullable = 3; object result = nonNullable;

换句话说,我认为你无法真正表达你想要做什么.

In other words, I don't think you can really express what you're trying to do.

更多推荐

如何创建 Nullable<T>从类型变量?

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

发布评论

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

>www.elefans.com

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