簡體   English   中英

為什么Nullable類型必須具有struct約束

[英]Why Nullable type must have struct constraint

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(SomeFunction<int>()==null);
        var temp = new SomeClass<int>();
        Console.WriteLine(temp.SomeFunction() == null);
        Console.ReadKey();
    }

    static public T? SomeFunction<T>() where T : struct
    {
        return null;
    }

    public class SomeClass<T> where T : struct 
    {
        public T? SomeFunction()
        {
            return null;
        }
    }
}

在上面的例子中,為什么可空類型需要struct約束?
我不明白為什么struct是正確的語法而不是對象或類。

因為Nullable<T> (或T? )也將T限制為結構。

因此,對於SomeFunction<T>的泛型類型參數T來滿足Nullable<T>的要求, SomeFunction<T> 必須聲明相同的約束。

這是另一個必須傳播約束的例子:

interface ISomeInterface { }
class MyClass<T> where T: ISomeInterface { }

class Program
{
    //MyClass's constaints must be "re-declared" here
    public MyClass<T> SomeFunction<T>() where T : ISomeInterface
    {
    }
}

為什么Nullable<T>這樣做? 因為可以為空的引用類型沒有任何意義。 Refence類型已經為空。

T? Nullable<T>簡寫, Nullable<T>要求T是結構:

public struct Nullable<T> where T : struct

Nullable<T>是一個結構(參見MSDN ),但它是唯一不滿足結構約束的結構。 另外,當使用類或結構約束時,不能將Nullable用作泛型類型參數。

Nullable<T>的基本思想是擁有一個可以包含T的存儲位置,或者可以表示“缺少值”

暫無
暫無

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

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