C#可空类型和Value属性 [英] C# Nullable Types and the Value property

查看:441
本文介绍了C#可空类型和Value属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当/如果必须获得包含在可空类型的值时,可以使用上可空类型Value属性上有点不清楚。请看下面的例子:

 诠释? X = 10; 

Console.WriteLine(+ x.Value的'X'是值);
Console.WriteLine('x'的值是+ X);



这两个返回相同的值(10)。



不过,如果我最初集合X为null,第一个Console.WriteLine抛出一个异常,而第二个则没有。



所以,我的问题是这个。什么是使用.Value属性点?它似乎并不需要得到实际值(即使它为空),如果该值确实是空会抛出异常。


解决方案

它的的,通常需要 - 只是没有你的具体情况。类型的X 可空< INT> ,而不是 INT - 而且也没有的的距离转换可空< T> T

让我们来看看,虽然发生的事情在你的榜样。您的最后一行被转换为:

  Console.WriteLine(string.Concat(值X是, X)); 

这是拳击 X ,这将导致的或者的盒装 INT 的空引用...这两者都是由处理string.Concat



在你的的通过字符串连接转换为字符串,例如:如果你想:

  INT非空= x.Value; 



那么你的的必须使用属性 - 或有明确的转换,也可能是空合并运算符,或调用 GetValueOrDefault

  INT非空=(int)的X; 
INT替代= X? 20;
INT andAnother = x.GetValueOrDefault(20);


I'm a little unclear on when/if the Value property on nullable types must be used when getting the value contained in a nullable type. Consider the following example:

int? x = 10;

Console.WriteLine("The value of 'x' is " + x.Value);
Console.WriteLine("The value of 'x' is " + x);

Both of these return the same value (10).

However, if I initially set x to null, the first Console.WriteLine throws an exception and the second one does not.

So, my question is this. What is the point of using the .Value property? It doesn't appear to be needed to get the actual value (even if it's null) and will throw an exception if the value is indeed null.

解决方案

It is needed usually - just not in your particular case. The type of x is Nullable<int>, not int - and there's no implicit conversion from Nullable<T> to T.

Let's look at what's happening in your example though. Your final line is being converted into:

Console.WriteLine(string.Concat("The value of 'x' is ", x));

That's boxing x, which will result in either a boxed int or a null reference... both of which are handled by string.Concat.

When you're not converting to a string via string concatenation, e.g. if you wanted:

int nonNullable = x.Value;

then you do have to use the Value property - or an explicit cast, or possibly a null coalescing operator, or a call to GetValueOrDefault:

int nonNullable = (int) x;
int alternative = x ?? 20;
int andAnother = x.GetValueOrDefault(20);

这篇关于C#可空类型和Value属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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