[英]Question about tekpub Mastering C#4.0 series 2
我試圖使以下文字盡可能准確,就像我從視頻培訓中聽到的那樣
http://shop.tekpub.com/products/csharp4
interface IFoo<in T>
{
void TakeAnInstanceOfT(T instance);
}
class Program
{
static void Main(string[] args)
{
IFoo<Fruit> fruit = null;
IFoo<Apple> apple = fruit; // <<< The following description was used
// <<< to explain this line.
// Apple is fruit.
// That's ok. Because anytime when fruit is expected to be
// passed in, is perfectly happy
// if you actually pass-in apple
}
}
問題>根據我的理解,下面陳述的原因
IFoo<Apple> apple = fruit;
正確是因為接口IFoo接受了協方差參數。 換句話說,它允許您傳入T的父類的實例。同時,視頻解釋告訴我完全相反的事情。
我希望作者說以下話(這種情況下我應該錯了:)
IFoo<Apple>
,只要期望有蘋果,您就可以通過。
不確定視頻,但這是一個解釋。 假設您有以下實現:
public class FruitImpl : IFoo<Fruit>
{
public void TakeAnInstanceOfT(Fruit instance)
{
}
}
public class AppleImpl : IFoo<Apple>
{
public void TakeAnInstanceOfT(Apple instance)
{
}
}
現在假設您這樣做:
IFoo<Fruit> fruit = new FruitImpl();
IFoo<Apple> apple = fruit;
如果我們再調用apple.TakeAnInstanceOfT(new Apple())
(您必須傳入Apple的實例,因為它現在已被強類型輸入為IFoo<Apple>
),那么FruitImpl
的方法將被調用(請記住,Apple指向一個(例如FruitImpl
實例),您將把Apple
的實例傳遞給接受完全合法的Fruit
的方法。 說得通?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.