如何将一个可空的整型转换为整型?假设我有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是整数。

其他回答

GetValueOrDefault ()

检索对象的值。如果它为null,则返回int的默认值,即0。

例子:

v2 = v1.GetValueOrDefault ();

可以使用Value属性进行赋值。

v2 = v1.Value;

就我而言,最好的解决方案是使用GetValueOrDefault()方法。

v2 = v1.GetValueOrDefault();
 int v2= Int32.Parse(v1.ToString());

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