如何将一个可空的整型转换为整型?假设我有2种类型的int如下:
int? v1;
int v2;
我想把v1的值赋给v2。V2 = v1;将导致错误。如何将v1转换为v2?
如何将一个可空的整型转换为整型?假设我有2种类型的int如下:
int? v1;
int v2;
我想把v1的值赋给v2。V2 = v1;将导致错误。如何将v1转换为v2?
当前回答
在c# 7.1及以后版本中,类型可以通过使用默认字面值而不是默认操作符来推断,因此它可以写成如下:
v2 = v1 ?? default;
其他回答
如果v2不为空,它将把v1的值赋给v2,否则它将采用默认值为零。
v2=v1??0
或者下面是另一种写法。
v2 = v1.HasValue?v1:0
根据你的使用上下文,你可以使用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.
你可以这样做
v2 = v1.HasValue ? v1.Value : v2;
正常的TypeConversion将抛出异常
Eg:
int y = 5;
int? x = null;
y = x.value; //It will throw "Nullable object must have a value"
Console.WriteLine(y);
使用Convert.ToInt32()方法
int y = 5;
int? x = null;
y = x.Convert.ToInt32(x);
Console.WriteLine(y);
这将返回0作为输出,因为y是整数。
v1和v2之间的简单转换是不可能的,因为v1的值域比v2大。它是v1能容纳的所有东西加上零状态。要进行转换,您需要显式地声明int中的哪个值将用于映射null状态。最简单的方法是??操作符
v2 = v1 ?? 0; // maps null of v1 to 0
这也可以用长形式表示
int v2;
if (v1.HasValue) {
v2 = v1.Value;
} else {
v2 = 0;
}