是否有可能欺骗 C# 编译器将 Nullable<T> 装箱?struct ant 不是它的价值吗? [英] Is it possible to cheat C# compiler to box Nullable<T> struct ant not its value?

查看:84
本文介绍了是否有可能欺骗 C# 编译器将 Nullable<T> 装箱?struct ant 不是它的价值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,这个问题可能看起来很奇怪.确实如此.
但我坚信,此类 hack 有助于理解语言和 .net 平台.

Well, the question may seem odd. And it really is.
Yet I strongly believe that such hacks help in understanding the language and .net platform.

C# 编译器处理可空类型的方式暗示了这个问题.

It is how C# compiler treats nullable types implies this question.

Nullable 是一个结构体.但是编译器包装的不是这个结构,而是它所持有的值,或者只是空引用.

Nullable<T> is a struct. But compiler boxes not this struct but the value it holds or just null reference.

在装箱的 Nullable 的情况下,拆箱将如何工作也很有趣.

It is also intersting how unboxing will work in the case of the boxed Nullable.

Nullable<int> myInt = boxedStruct as Nullable<int>;

这里我认为 boxedStruct 不是装箱的 int 而是整个结构体.

here I meen that boxedStruct is not a boxed int but the whole struct.

好吧,可能是 Nullables 在 CLR 级别被区别对待,因为我无法理解下面程序的输出.

Well, may be Nullables are treated differently at CLR level because I cannot understand the ouptut of the program below.

class Program
{
    public static bool? Property { get; set; }

    static void Main(string[] args)
    {
        Property = true;

        var valueType = typeof (Program).GetProperty("Property").GetValue(null).GetType();
        var propType = typeof (Program).GetProperty("Property").PropertyType;

        Console.WriteLine("Value's type '{0}' is the same as type of the property '{1}' - '{2}'", valueType, propType, valueType == propType);
        Console.ReadKey();
    }
}

输出:

值的类型System.Boolean"与属性的类型相同'System.Nullable`1[System.Boolean]' - '假'

Value's type 'System.Boolean' is the same as type of the property 'System.Nullable`1[System.Boolean]' - 'False'

更新:

这里的规范 (ECMA 335) 说的是:

Here what specification (ECMA 335) says:

I.8.2.4 值的装箱和拆箱
...
如果值类型是可空类型——定义为值类型的实例化System.Nullable——结果是一个空引用或其 T 类型的 Value 属性,取决于其 HasValue 属性(分别为假和真).

I.8.2.4 Boxing and unboxing of values
...
If the value type is a nullable type—defined as an instantiation of the value type System.Nullable—the result is a null reference or bitwise copy of its Value property of type T, depending on its HasValue property (false and true, respectively).

所以如果我理解正确的话.Nullable<T> strcut 不能在 .Net Framework 中装箱,不仅 C# 编译器不可能,CLR 也是如此.

So if I understand this correctly. Nullable<T> strcut cannot be boxed in .Net Framework and it's not just impossible with C# compiler but with CLR as well.

推荐答案

我猜你想问的问题是:

是否可以将 Nullable 值装箱而不产生空引用或装箱的 int 值,而是实际装箱的 Nullable?

Can you box a Nullable<int> value without producing a null reference or a boxed int value, but instead an actually boxed Nullable<int>?

没有

这篇关于是否有可能欺骗 C# 编译器将 Nullable&lt;T&gt; 装箱?struct ant 不是它的价值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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