如何CLR可以分配一个空值的结构时,绕过抛出错误? [英] How CLR can bypass throwing error when assigning a null value to the struct?
问题描述
我想了解这段代码一件事:
可空<&的Int32 GT; X = 5;
可空<&的Int32 GT; Y = NULL;
Console.WriteLine(X:的HasValue = {0},值= {1},x.HasValue,x.Value);
Console.WriteLine(Y:的HasValue = {0},值= {1},y.HasValue,y.GetValueOrDefault());
和输出是:
X:的HasValue = TRUE,值= 5 $ b $通过:的HasValue =假,值= 0
和,当你通过我不明白的东西空
到是
,我相信它会调用公共静态隐运营商可空< T>(T值)
但这种方法的定义初始化一个新的结构通过值
被分配空
但是构造方法不检查它是否为空或不那么它可以分配默认(T)
为值
。
为什么我们甚至可以将空在这里struct和它工作正常?
你们可以什么,我错过了这里?我不明白它是如何绕过刚空
并返回默认值。
可空码内定义
相信它会调用公共静态隐运营商可为空(T值)
块引用>
没有没有,因为
T
是的Int32
在这种情况下,和空
不是的Int32
。它只是离开是
变量默认情况下,这意味着一个结构,所有字节0
。这将导致有一个的HasValue
返回假
。
$ B $一个结构b您真的不能通
空
来一个结构,但C#编译器将其转换为你默认initalization。I am trying to understand one thing in this code:
Nullable<Int32> x = 5; Nullable<Int32> y = null; Console.WriteLine("x: HasValue={0}, Value={1}", x.HasValue, x.Value); Console.WriteLine("y: HasValue={0}, Value={1}", y.HasValue, y.GetValueOrDefault());
And Output is:
x: HasValue=True, Value=5 y: HasValue=False, Value=0
And the thing that I don't understand when you pass
null
toy
, I believe it callspublic static implicit operator Nullable<T>(T value)
but the definition of this method initializes a new struct passingvalue
which is assignednull
however constructor method doesn't check whether it is null or not so it can assigndefault(T)
tovalue
.How come we can even assign null to struct here and it works fine?
Can you guys what I am missing out here? I don't understand how it just bypassed
null
and returned default value.Nullable code inner definition:
解决方案believe it calls public static implicit operator Nullable(T value)
No it doesn't, because
T
isInt32
in this case, andnull
is not anInt32
. It just leaves they
variable default, which means for a struct that all bytes are0
. This results in a struct that has aHasValue
that returnsfalse
.You can't really pass
null
to a struct, but the C# compiler is converting this for you to a default initalization.这篇关于如何CLR可以分配一个空值的结构时,绕过抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!