开发者

Question about contravariant parameter used in method parameters

I have read a good article introducing the covariance and contracovariance

http://bartdesmet.net/blogs/bart/archive/2009/04/15/14377.aspx

Contravariant parameters should only occur in input positions: method parameters, set-only properties or indexers.

class SubClass : BaseClass {
    public void P开发者_如何转开发rintSubClass() {}
}
class BaseClass{
}

static class Sample {

    public static void PrintMeNow (SubClass c)
    {
        c.PrintSubClass();
    }
}

static void Main(string[] args)
{
    SubClass  sc = new SubClass();
    BaseClass bc = new BaseClass();

    Sample.PrintMeNow(sc); // ok
    Sample.PrintMeNow(bc); // Line A (not-ok Question: Is this contravariance?)
}

Based on my understanding of the contravariance, I have put the code as above. Obviously, the line A is not correct and I mis-interpret the concept of contravariance.

Which part is wrong? What concept is not understood correctly? How to make it right?


Covariance and contravariance are about generic parameters; your code has nothing to do with it.

It doesn't work because bc isn't a SubClass.
All SubClasses are BaseClasses, but not all BaseClasses are SubClasses.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜