C# casting an inherited Generic interface

后端 未结 2 1351
既然无缘
既然无缘 2020-12-06 01:18

I\'m having some trouble getting my head around casting an interface I\'ve come up with. It\'s an MVP design for C# Windows Forms. I have an IView class which I implement o

2条回答
  •  爱一瞬间的悲伤
    2020-12-06 01:46

    The problem is the generic type parameter. If you make the interface parameter covariant then the cast will work.

    This is accomplished by adding the out keyword, like so:

    interface IPresenter where V : IView
    {
        void PresBlah();
    
    }
    

    You can learn more about how this works with the following MSDN article: Covariance and Contravariance in Generics. The section Generic Interfaces with Covariant Type Parameters specifically applies to your question.

    Update: Make sure you check the comments between @phoog and me. If your actual code accepts a V as an input, you will be unable to make it covariant. The referenced article and @phoog's answer explains this case in further detail.

提交回复
热议问题