我有一個方法應該回傳一個可為空的參考型別或一個可為空的值型別:
private static T? FooValueOrReferenceType<T>(string input)
{
return null;
// the code above show this error
// Cannot convert null to type parameter 'T' because it could be
// a non-nullable value type. Consider using 'default(T)' instead.
}
我不明白為什么我不能回傳 null,因為我在專案中啟用了可為空的值型別
我知道添加約束where T : struct, class
可以解決問題,但我想了解原因。
我注意到這個方法簽名:
private static T? FooValueType<T>(string input) where T : struct
編譯為:
private static Nullable<T> FooValueType<T>([System.Runtime.CompilerServices.Nullable(1)] string input) where T : struct
和這個:
private static T? FooReferenceType<T>(string input) where T : class
編譯為:
private static T FooReferenceType<T>(string input) where T : class
這一切背后的原因是什么?
有一些與此類似的問題,但對于像我這樣的菜鳥來說,答案并不清楚。
uj5u.com熱心網友回復:
歸根結底,可空性對于參考型別和值型別意味著兩個根本不同的東西。對于值型別,T?
意味著-圍繞aNullable<T>
的包裝層,帶有一些編譯器巫術 - 對于參考型別,意味著簡單,但帶有一些額外的編譯器背景關系(以及添加的屬性,以傳達該意圖)。在 IL中根本無法同時表達這兩個東西,并且不能在 IL 中互換使用(即使 C# 讓它看起來像你可以)。最終,“你就是不能,IL 不是那樣作業的”。T
T?
T
Nullable<T>
T
你的兩個實驗很好地展示了: class
這: struct
兩個不兼容的變體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/515704.html
標籤:C#
下一篇:獲取url中的所有引數