如何转换C#可空INT为int [英] How to convert C# nullable int to 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!