2010-02-12 52 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()