2010-02-12 82 views

回答

0

运行该地看到,int?是值类型:

class Program 
{ 
    static int? nullInt; 

    static void Main(string[] args) 
    { 
     nullInt = 2; 
     Console.WriteLine(string.Format("{0} + 3 != {1}", nullInt, DoMath(nullInt , 3).ToString())); 
     Console.WriteLine(string.Format("{0} * 3 = {1}" , nullInt , DoMultiply(nullInt , 3).ToString())); 

     nullInt = null; 
     Console.WriteLine(string.Format("{0} + 3 != {1}" , nullInt , DoMath(nullInt , 3).ToString())); 
     Console.WriteLine(string.Format("{0} * 3 = {1}" , nullInt , DoMultiply(nullInt , 3).ToString())); 

     Console.ReadLine(); 
    } 

    static int? DoMath(int? x , int y) 
    { 
     if (x.HasValue) 
     { 
      return (++x) + y; 
     } 
     else 
      return y; 
    } 

    static int DoMultiply(int? x , int y) 
    { 
     if (x.HasValue) 
     { 
      return (int)x * y; 
     } 
     else 
      return 0; 
    } 
} 

我发现这是非常有趣的,并就一些聪明的用途。

什么?确实是创建一个可为空的引用,否则不可为空值类型。这就像有一个可以检查的指针 - HasValue(一个布尔值)? Nullable<T>的好处在于Value属性不需要转换为原始类型 - 该工作在可空结构中完成。

2

int?Nullable<int>相同,它是一个结构,即值类型。这里没有转换为引用类型。

下面是可空的,从MSDN定义:

[SerializableAttribute] 
public struct Nullable<T> where T : struct, new()