Question about tekpub Mastering C#4.0 series 2
I have tried to make the following text as accurate as I could hear from the video training
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
}
}
Question> Based on my understand, the reason why the following statement
IFoo<Apple> apple = fruit;
is correct is because that the interface IFoo accepts contra-variance parameters. In other words, it allows you to pass in instances of parent class o开发者_C百科f T. While, the video interpretation tells me the exact opposite thing.
I expect the author to say the following (I should be wrong this case:)
IFoo<Apple>
, anytime when Apple is expected, you are allowed to pass in fruits.
Not sure about the video, but here's an explanation. Say you have these implementations:
public class FruitImpl : IFoo<Fruit>
{
public void TakeAnInstanceOfT(Fruit instance)
{
}
}
public class AppleImpl : IFoo<Apple>
{
public void TakeAnInstanceOfT(Apple instance)
{
}
}
Now let's say you do this:
IFoo<Fruit> fruit = new FruitImpl();
IFoo<Apple> apple = fruit;
if we then call apple.TakeAnInstanceOfT(new Apple())
(you have to pass in an instance of Apple, since it's now strongly typed to IFoo<Apple>
) then the method in FruitImpl
will get called (remember, apple points to an instance of FruitImpl
) and you'll be passing in an instance of an Apple
to a method that accepts a Fruit
which is totally legal. Makes sense?
精彩评论