[C#] Nullable 型別

  • 6670
  • 0
  • 2009-12-13

摘要:[C#] 可為 NULL 的型別

在 C# 中的變數中,如整數、浮點數、佈林值、日期等型別不能設定其值為 null,就是說這些資料型別,

在初始化時必須有明確的值存在;如果沒有宣告初值,則系統會自動依其型別賦予初值。

例如:

//類別層級變數,會預設初始值
private int h; //宣告後 h = 0

private void MethodA(){
   //區域變數需指定初始值
   int iValue = 0;
}

 

話說回來,既然是值型別,為何還要將之設為 null 呢?

大都與資料表中欄位設定有關,資料欄位可以有資料,也可以不指定任何資料,此時該欄位沒有任何值。

例如:婚姻狀況的欄位,可以明確的指定「是」或「否」,但是如果真的沒有填寫,該欄位應以 null 表示。

所以,如何指定值型別為 null  值?參考以下: 

int? n;//宣告變數
n = 8; //可以指定為數值
n = null; //也可指定為 null

 

指定為 null  的變數型別,其實是一個特殊的型別,它和其他的資料型別是不相同的,因此不可以將其指派給

其他不相同的資料型別,否則會產生錯誤。

例如:

int? n1;
int n2 = 1;
n1 = null;
n2 = n1; //錯誤

 

Link

 

補充:

1.

class UsingNullable
{
    static void Main(string[] args)
    {
        UsingNullable theUsingNullable = new UsingNullable(); 
        NullableValue theNullableValue = new NullableValue();        

        Console.WriteLine(
            "intNullable1 = " + 
            theUsingNullable.getNullableValue(theNullableValue.intNullable1)           
            ) ;
        Console.WriteLine(
            "intNullable2 = " +
            theUsingNullable.getNullableValue(theNullableValue.intNullable2)
            );
        Console.WriteLine(
            "dblNullable1 = " +
            theUsingNullable.getNullableValue(theNullableValue.dblNullable1)
            );
        Console.WriteLine(
            "dblNullable2 = " +
            theUsingNullable.getNullableValue(theNullableValue.dblNullable2)
            );
        Console.ReadLine(); 
    }
    string getNullableValue(int? pValue)
    {
        if (pValue.HasValue == true)
           return pValue.Value.ToString(); 
        else
           return "null"; 
    }
    string getNullableValue(double? pValue)
    {
        if (pValue.HasValue == true)
            return pValue.Value.ToString();
        else
            return "null";
    }
}
class NullableValue
{
    public int? intNullable1 = 100;
    public Nullable<int> intNullable2 = null;

    public double? dblNullable1 = null;
    public Nullable<double> dblNullable2 = 123.456;   
}

輸出結果

 

 

三小俠  小弟獻醜,歡迎指教