我在使用 C# 实现接口时遇到问题:
public interface IFooable
{
public (IFooable left, IFooable right) FooWith(IFooable other);
}
Run Code Online (Sandbox Code Playgroud)
然后在我的具体课程中,我有
class Concrete
{
public (Concrete left, Concrete right) FooWith(Concrete other)
{
return GoFooSomewhereElse(...);
}
}
Run Code Online (Sandbox Code Playgroud)
但在我的测试中,编译器告诉我Concrete没有实现 FooWith 函数。
我真的不明白发生了什么,因为我对 C# 很陌生,很容易被这门语言搞糊涂!
我发现了类似的问题(例如为什么我不能重写我的接口方法?),但它们没有解决我的问题。
根据里氏替换原则,超类对象应该可以用子类对象替换,而不会破坏软件的功能。
您的Concrete类显然没有实现该接口,因为如果我尝试将某个AnotherFooable类的参数传递给FooWith()方法,它将不起作用。
相反,你可以使其通用:
public interface IFooable<T>
{
public (T left, T right) FooWith(T other);
}
class Concrete : IFooable<Concrete>
{
public (Concrete left, Concrete right) FooWith(Concrete other)
{
return GoFooSomewhereElse(...);
}
}
Run Code Online (Sandbox Code Playgroud)
FooWith()如果您希望方法仅接受同一类的参数(如您的示例中所示),您还可以对泛型类型参数进行限制Concrete.FooWith(Concrete, Concrete):
public interface IFooable<T> where T : IFooable<T>
...
Run Code Online (Sandbox Code Playgroud)