我加了這個,希望能夠多一點 light由Jon和Marc提供的答案。
考慮這種非泛型方法:
public static void SetToNull(ref ISomeInterface obj) {
obj = null;
}
嗯...設置ref
參數設置爲null。這隻適用於參考類型,對嗎? (嗯,或者對於Nullable<T>
;但是讓我們忽略這種情況以使事情變得簡單)。因此,此方法編譯的事實告訴我們,聲明爲某種接口類型的變量必須被視爲引用類型。
關鍵短語這裏「聲明」:考慮這個試圖調用上述方法:
var x = new SomeStruct();
// This line does not compile:
// "Cannot convert from ref SomeStruct to ref ISomeInterface" --
// since x is declared to be of type SomeStruct, it cannot be passed
// to a method that wants a parameter of type ref ISomeInterface.
SetToNull(ref x);
當然,你不能在上面的代碼通過x
到SetToNull
原因是x
會需要聲明爲ISomeInterface
您能夠通過ref x
和而不是,因爲編譯器神奇地知道SetToNull
包含行obj = null
。但是,僅僅加強我的觀點的方式:在obj = null
線是合法正是因爲這將是非法傳遞變量不聲明爲ISomeInterface
的方法。
換句話說,如果一個變量聲明爲ISomeInterface
,它可以設置爲空,純粹和簡單。這是因爲接口是引用類型 - 因此,將對象聲明爲接口並將其分配給值類型的值對象框。
現在,在另一方面,考慮這個假設的泛型方法:
// This method does not compile:
// "Cannot convert null to type parameter 'T' because it could be
// a non-nullable value type. Consider using 'default(T)' instead." --
// since this method could take a variable declared as, e.g., a SomeStruct,
// the compiler cannot assume a null assignment is legal.
public static void SetToNull<T>(ref T obj) where T : ISomeInterface {
obj = null;
}
我假設。不完全確定是什麼讓我懷疑會是這樣。只是以爲我會把它扔出去,以防萬一別人有奇怪的想法。 – Sekhat 2010-06-13 15:51:46
給男人一個工具來獲得答案(紅門反射器),他會有生命的答案。但給他一個答案,他會回來更多的問題和更多的SO重點... – 2010-06-13 17:24:27
@Ben:另一方面,給男人一個工具,他們將不得不每次檢查它,不確定。給一個男人一個解釋*,他們可以爲自己推理一下。 – 2010-06-13 17:39:04