如何将一个可空的整型转换为整型?假设我有2种类型的int如下:
int? v1;
int v2;
我想把v1的值赋给v2。V2 = v1;将导致错误。如何将v1转换为v2?
如何将一个可空的整型转换为整型?假设我有2种类型的int如下:
int? v1;
int v2;
我想把v1的值赋给v2。V2 = v1;将导致错误。如何将v1转换为v2?
当前回答
到目前为止,其他答案都是正确的;我只是想再加一个稍微干净一点的:
v2 = v1 ?? default(int);
任何Nullable<T>都可以隐式转换为它的T,前提是被计算的整个表达式永远不会导致对ValueType的空赋值。那么,空合并操作符??只是三元运算符的语法糖:
v2 = v1 == null ? default(int) : v1.Value;
...这反过来是if/else的语法糖:
if(v1==null)
v2 = default(int);
else
v2 = v1.Value;
此外,在。net 4.0中,Nullable<T>有一个"GetValueOrDefault()"方法,这是一个空安全的getter,基本上执行如上所示的空合并,所以这也是有效的:
v2 = v1.GetValueOrDefault();
其他回答
你所需要的是…
v2= v1.GetValueOrDefault();
像这样,
if(v1.HasValue)
v2=v1.Value
根据你的使用上下文,你可以使用c# 7的模式匹配特性:
int? v1 = 100;
if (v1 is int v2)
{
Console.WriteLine($"I'm not nullable anymore: {v2}");
}
编辑:
由于有些人没有留下解释就投了反对票,我想添加一些细节来解释将此作为可行解决方案的基本原理。
C# 7's pattern matching now allows us check the type of a value and cast it implicitly. In the above snippet, the if-condition will only pass when the value stored in v1 is type-compatible to the type for v2, which in this case is int. It follows that when the value for v1 is null, the if-condition will fail since null cannot be assigned to an int. More properly, null is not an int. I'd like to highlight that the that this solution may not always be the optimal choice. As I suggest, I believe this will depend on the developer's exact usage context. If you already have an int? and want to conditionally operate on its value if-and-only-if the assigned value is not null (this is the only time it is safe to convert a nullable int to a regular int without losing information), then pattern matching is perhaps one of the most concise ways to do this.
我正在使用c# 9和。net 5作为示例
foo是可空的int,我需要得到foo的int值
var foo = (context as AccountTransfer).TransferSide;
int value2 = 0;
if (foo != null)
{
value2 = foo.Value;
}
详见https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types#examination-of-an-instance-of-a-nullable-value-type
如果你知道v1有一个值,你可以使用value属性:
v2 = v1.Value;
如果有,使用GetValueOrDefault方法将赋值,否则为类型的默认值,或者您指定的默认值:
v2 = v1.GetValueOrDefault(); // assigns zero if v1 has no value
v2 = v1.GetValueOrDefault(-1); // assigns -1 if v1 has no value
你可以使用HasValue属性来检查v1是否有值:
if (v1.HasValue) {
v2 = v1.Value;
}
GetValueOrDefault(T)方法也有语言支持:
v2 = v1 ?? -1;