C#可空类型和Value属性

编程入门 行业动态 更新时间:2024-10-25 19:37:37
本文介绍了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属性

本文发布于:2023-11-08 08:00:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568805.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!