鑑於這種神奇的接口:在C#4.0中,爲什麼方法中的out參數不能協變?
public interface IHat<out TRabbit>
{
TRabbit Take();
}
而這種類層次結構:
public class Rabbit { }
public class WhiteRabbit : Rabbit { }
現在我可以編譯這樣的:
IHat<WhiteRabbit> hat1 = null;
IHat<Rabbit> hat2 = hat1;
這是偉大的。但是,如果我定義不同的接口:
public interface IHat<out TRabbit>
{
bool Take(out TRabbit r);
}
我表明帽子可能是空的,用一個單獨的布爾返回值(以前的版本或許會已返回一個空帽子空兔)。但我仍然只輸出一隻兔子,所以沒有做任何與之前版本邏輯上不同的東西。
CTP中的C#4.0編譯器在接口定義中給出了錯誤 - 它要求「out」方法參數爲不變類型。難道這是不允許的嗎?還是在未來的版本中可以解決?
有關信息,我發現多個博客等說相同,但沒有評論來自「官方」MS來源。我相當確信它是正確的,但是...... C#4.0差異仍然基於CLI規則。 – 2009-02-09 12:03:08