[英]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.