如何转换C#可空INT为int

编程入门 行业动态 更新时间:2024-10-26 16:21:17
本文介绍了如何转换C#可空INT为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我要如何转换成一个可空 INT 到 INT ?假设我有2 int类型如下的:

How do I convert a nullable int to an int? Suppose I have 2 type of int as below:

int? v1; int v2;

我要分配 V1 的价值 V2 。 V2 = V1; 将导致错误。如何转换 V1 到 V2 ?

I want to assign v1's value to v2. v2 = v1; will cause an error. How do I convert v1 to v2?

推荐答案

其他答案为止是正确的;我只是想增加一个这是稍微干净:

The other answers so far are all correct; I just wanted to add one more that's slightly cleaner:

v2 = v1 ?? default(int);

任何可空< T> 隐式转换为它的 T ,只要全程前pression正在评估不能得到空值赋值给一个值类型。因此,空合并运算符 ?? 是三元操作只是语法糖:

Any Nullable<T> is implicitly convertible to its T, PROVIDED that the entire expression being evaluated can never result in a null assignment to a ValueType. So, the null-coalescing operator ?? is just syntax sugar for the ternary operator:

v2 = v1 == null ? default(int) : v1;

...而这又是语法糖的的if / else:

...which is in turn syntax sugar for an if/else:

if(v1==null) v2 = default(int); else v2 = v1;

另外,由于.NET 4.0,可空&LT; T&GT; 有一个GetValueOrDefault()方法,这是基本上执行的空值空安全的吸上述合并显示,所以这个工程太:

Also, as of .NET 4.0, Nullable<T> has a "GetValueOrDefault()" method, which is a null-safe getter that basically performs the null-coalescing shown above, so this works too:

v2 = v1.GetValueOrDefault();

更多推荐

如何转换C#可空INT为int

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

发布评论

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

>www.elefans.com

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