2011-04-25 64 views
5

我想知道如何隱式轉換可爲空的「?」變量分區。給出這個例子隱式從Nullable轉換爲正常,有什麼想法?

int? x = 5; 

int y = x; //this gonna fail, !!! 

我需要一些方法來覆蓋=參數

,可惜=參數不是重載...任何建議

我使用C#

+0

這是什麼語言?或者是這種語言不可知的,我沒有注意到? – 2011-04-25 22:49:41

回答

7

這是可以實現的implicit cast operator,只求或您定義的類型。例如,做這樣的事情..

public class NullableExtensions 
{ 
    public static implicit operator int(int? value) 
    { 
     return value ?? default(int); 
    } 
} 

..將返回CS0556編譯錯誤,因爲投不包括用戶定義類型。

你可以做的最接近的是定義自己的空類型,它包含一個隱式類型轉換操作符:

public struct ImplicitNullable<T> where T: struct 
{ 
    public bool HasValue { get { return this._value.HasValue; } } 
    public T Value { get { return this._value.Value; } } 

    public ImplicitNullable(T value) : this() { this._value = value; } 
    public ImplicitNullable(Nullable<T> value) : this() { this._value = value; } 

    public static implicit operator ImplicitNullable<T>(T value) { return new ImplicitNullable<T>(value); } 
    public static implicit operator ImplicitNullable<T>(Nullable<T> value) { return new ImplicitNullable<T>(value); } 

    public static implicit operator T(ImplicitNullable<T> value) { return value._value ?? default(T); } 
    public static implicit operator Nullable<T>(ImplicitNullable<T> value) { return value._value; } 

    private Nullable<T> _value { get; set; } 

    // Should define other Nullable<T> members, especially 
    // Equals and GetHashCode to avoid boxing 
} 

注意,雖然有可能寫這樣的代碼,它可能會導致難以跟蹤的錯誤。如果值爲null,我會建議使用明確的轉換,或拋出異常。

之後,您可以轉換爲從預期:

static void Main() 
{ 
    int myInt = 1; 
    int? nullableInt = 2; 

    ImplicitNullable<int> implicitInt; 

    // Convert from int or int? 
    implicitInt = myInt; 
    implicitInt = nullableInt; 

    // Convert to int or int? 
    myInt = implicitInt; 
    nullableInt = implicitInt; 
} 
11

你有兩個選項,直接訪問該值(如果您確實知道它不爲空):

int y = x.Value; 

或者,使用空合併運算符:

int y = x ?? 0; // 0 if null... 
+0

好的,這是對的,但我需要它隱式地完成,因爲有很多代碼使用它。 – 2011-04-25 22:57:24

+0

@Mustafa - 如果你知道如何做到這一點,請告訴我;)在C#中,你不能重載賦值運算符。你也不能擴展'int'。你如何解決這個問題將取決於你的應用程序的架構。你可以用其他方式去替換所有'int's'int',因爲'int'會隱式地轉換爲'int?'? – 2011-04-25 23:06:36

+0

@Mustafa:你不能重寫'='操作符,它不是一種方法。如果你使用'.Equals'方法比較值,那麼你可以寫一個覆蓋它。 – tobias86 2011-04-25 23:07:37

1

我假設這是C#

你需要或者投,或使用.value

int? x = 5; 
int y; 

if(x.HasValue) 
    y = x.Value; 
else 
    throw new//... handle error or something 
3

等待,我很困惑...

你爲什麼不只是使用GetValueOrDefault

+0

原因是,我有一個已經寫好的代碼,我不想在每個道具後面都輸入「GetValueOrDefault()」,謝謝 – 2011-04-27 18:05:20

相關問題