如何null文本到System.Nullable 1所述的转让; T>键入get通过。NET(C#)如何处理? [英] How does the assignment of the null literal to a System.Nullable<T> type get handled by .Net (C#)?

查看:187
本文介绍了如何null文本到System.Nullable 1所述的转让; T>键入get通过。NET(C#)如何处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有人知道C#编译器是如何处理以下任务:

I was wondering if anyone knows how the C# compiler handles the following assignment:

int? myInt = null;



我的假设是,有一个隐式转换进行的,但我无法弄清楚如何null文本分配被处理。我dissasembled的System.Nullable对象,发现隐含的经营者重写这个:

My assumption is that there is an implicit conversion performed, but I cannot figure out how the null literal assignment is handled. I dissasembled the System.Nullable object and found the implicit operator is overriden to this:

public static implicit operator T?(T value)  {
    return new T?(value);  
}



一旦调用,这将尝试火二级构造:

Once called this would try to fire the secondary constructor:

public Nullable(T value) {
    this.value = value;
    this.hasValue = true; 
}



这就是我的困惑进场...... THIS.VALUE是一些值类型,不能为空。

Which is where my confusion comes into play... this.value is of some value type and cannot be null.

因此,没有人知道这个魔术是如何发生的?还是我在错误的假设,二次调用构造函数?是否默认的构造函数被调用,因为编译器知道它无法比拟的第二个构造器与null文本(导致敏被分配到一个新的空可空)?

So, does anyone know how this "magic" takes place... or am I wrong in assuming that the secondary constructor is called? Does the default constructor get called because the compiler knows that it cannot match the second contructor's signature with the null literal (resulting in myInt being assigned to a new "null" Nullable)?

推荐答案

语句:

int? myInt = null;



被编译为:

Gets compiled as:

  .locals init (valuetype [mscorlib]System.Nullable`1<int32> V_0)
  IL_0000:  ldloca.s   V_0
  IL_0002:  initobj    valuetype [mscorlib]System.Nullable`1<int32>



其中,的根据MSDN ,意味着«指定地址为初始化值类型的各个领域空引用或相应的原始类型的0。»

Which, according to the MSDN, means «Initialize each field of the value type at a specified address to a null reference or a 0 of the appropriate primitive type.»

所以这里没有构造函数或转换。的HasValue将返回false,并试图获得其价值将引发InvalidOperationException。除非你使用当然GetValueOrDefault。

So there's no constructor or conversion here. HasValue will return false, and trying to get its Value will throw an InvalidOperationException. Unless you use GetValueOrDefault of course.

这篇关于如何null文本到System.Nullable 1所述的转让; T&GT;键入get通过。NET(C#)如何处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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