如何将一个可空的整型转换为整型?假设我有2种类型的int如下:

int? v1;  
int v2; 

我想把v1的值赋给v2。V2 = v1;将导致错误。如何将v1转换为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是整数。

其他回答

你可以这样做

v2 = v1.HasValue ? v1.Value : v2;

v2 = Convert.ToInt32(v1);

正常的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是整数。

Int nullable到Int的转换可以这样完成:

v2=(int)v1;

如果给定类型的默认值是可接受的结果:

if (v1.HasValue)
    v2 = v1.GetValueOrDefault();

如果你想在结果为undefined时获得不同的默认值:

v2 = v1.GetValueOrDefault(255);    // or any valid value for int in place of 255

如果你只是想要返回值(不管方法是否失败):

v2 = v1.GetValueOrDefault();

net 4.7.2。: GetValueOrDefault()返回字段值,不进行任何检查。