簡體   English   中英

具有與Nullable相同的編譯器行為的C#自定義通用結構<T>

[英]C# Custom generic struct with same compiler behavior as Nullable<T>

用C#中的System.Nullable<T>看下面的示例。

int x = 5;
int? y = 3;
int? result = x + y; //no compiler warning

編譯器可以確定T是一個int ,因此可以使用運算符,這是有道理的。
同樣在

int x = 5;
int? y = 3;
bool result = x == y; //no compiler warning

這是有道理的,如果xnull ,則表達式將為false 編譯器不在乎。

現在,我試圖創建一個類似的Nullable<T>類。 我們稱之為Lookable<T>

[Serializable]
public struct Lookable<T> where T : struct
{
    public Lookable(T value)
    {
        Value = value;
    }

    public T Value { get; }

    public override bool Equals(object other)
    {
        return other != null && Value.Equals(other);
    }

    public override int GetHashCode()
    {
        return Value.GetHashCode();
    }

    public override string ToString()
    {
        return Value.ToString();
    }

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

    public static explicit operator T(Lookable<T> value)
    {
        return value.Value;
    }
}

這里的想法直接來自.NET的源代碼 就我而言,我只是省略了HasValue屬性。 現在,此示例將起作用:

int x = 6;
Lookable<int> y = x;
Lookable<int> z = 4;

編譯器可以在這里推斷類型,因為implicit operator正確嗎?
我不明白的是,此示例會使編譯器不滿意:

int x = 5;
Lookable<int> y = 3;
var result1 = x + y; //compile error
var result2 = x == y; //compile error

編譯器給我消息:

運算符不能應用於類型為' int '和' Lookable<int> '的操作數。

為什么不? 以及為什么可以使用Nullable<T>呢? 我在源代碼的任何地方都找不到它。 Lookable<T>是否也可能?

此代碼不在Nullable<T> ,而是在C#編譯器中,尤其是在規范中的“提升運算符”中,以及它們如何專門應用於System.Nullable<T> 規范參考在此答案中

您不能以自己的類型重現Nullable<T>行為。 它具有編譯器和運行時的特殊處理(裝箱等)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM