如何CLR可以分配一个空值的结构时,绕过抛出错误? [英] How CLR can bypass throwing error when assigning a null value to the struct?

查看:179
本文介绍了如何CLR可以分配一个空值的结构时,绕过抛出错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解这段代码一件事:

 可空<&的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和它工作正常?



你们可以什么,我错过了这里?我不明白它是如何绕过刚并返回默认值。



可空码内定义



http://codepaste.net/gtce6d


解决方案

相信它会调用公共静态隐运营商可为空(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 to y, I believe it calls public static implicit operator Nullable<T>(T value) but the definition of this method initializes a new struct passing value which is assigned null however constructor method doesn't check whether it is null or not so it can assign default(T) to value.

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:

http://codepaste.net/gtce6d

解决方案

believe it calls public static implicit operator Nullable(T value)

No it doesn't, because T is Int32 in this case, and null is not an Int32. It just leaves the y variable default, which means for a struct that all bytes are 0. This results in a struct that has a HasValue that returns false.

You can't really pass null to a struct, but the C# compiler is converting this for you to a default initalization.

这篇关于如何CLR可以分配一个空值的结构时,绕过抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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