2008-10-15 58 views
0

有沒有辦法在c#中聲明一個變量爲Nullable?初始化一個結構變量爲Nullable <int>

struct MyStruct {   
    int _yer, _ner; 

    public MyStruct() { 

     _yer = Nullable<int>; //This does not work. 
     _ner = 0; 
    } 
} 
+0

@sir psycho:記住你不能在c#中的struct中聲明顯式無參數構造函數 – Kev 2008-10-15 11:18:09

回答

5

_yer必須聲明爲int?或可爲空<int>。

int? _yer; 
    int _ner; 

    public MyStruct(int? ver, int ner) { 

     _yer = ver; 
     _ner = ner; 
    } 
} 

或者這樣:

Nullable<int> _yer; 
    int _ner; 

    public MyStruct(Nullable<int> ver, int ner) { 

     _yer = ver; 
     _ner = ner; 
    } 
} 

記住結構不能包含明確的參數構造函數。

error CS0568: Structs cannot contain explicit parameterless constructors 
1

嘗試聲明你的變量是這樣的:

int? yer; 
0

怎麼樣nullable types

struct MyStruct 
{ 
    private int? _yer, _ner; 
    public MyStruct(int? yer, int? ner) 
    { 
     _yer = yer; 
     _ner = ner; 
    } 
} 
0

嘗試聲明_yer類型可空開始,而不是作爲一個標準的INT。