A generic method can use contravariant/covariant types?

后端 未结 3 405
梦如初夏
梦如初夏 2020-12-31 19:00

I\'m writting a generalized method to use it in a special task at a T4 template. The method should allow me to use specialized types from a general interface. I thought abou

3条回答
  •  别那么骄傲
    2020-12-31 19:38

    Maybe you're looking for this:

    interface IGreatInterface where U : IAnInterface
    { 
        Object aMethodAlpha(U parameter);
    } 
    
    class SomeClass : IAnInterface { /*...*/ }
    
    class GreatClass : IGreatInterface
    {
        public Object aMethodAlpha(SomeClass parameter) {}
    }
    

    EDIT:

    Yes, you are right: if you define a generic method in an interface, you can't implement that method with a concrete method using a compatible type.

    How about using a delegate (since delegates support co- and contravariance):

    [example deleted because I got the variance backwards -- it doesn't work.]

提交回复
热议问题