Interface with generic parameter vs Interface with generic methods

前端 未结 4 1150
别那么骄傲
别那么骄傲 2020-12-08 02:34

Let\'s say I have such interface and concrete implementation

public interface IMyInterface
{
    T My();
}

public class MyConcrete : IMyInterface&l         


        
4条回答
  •  自闭症患者
    2020-12-08 02:50

    Your solution does not work for two reasons.

    First, an interface is a contract. When you implement IMyInterface2 you guarantee that you will implement a function named My that takes a generic type parameter and returns that type. MyConcrete2 does not do this.

    Second, C# generics do not allow any kind of type parameter specialization. (I do wish C# supported this.) This is a common thing in C++ templates where your example would compile, but any usages of MyConcrete2 would fail to compile if they don't call My with a string.

提交回复
热议问题