【发布时间】:2020-07-06 21:10:56
【问题描述】:
我正在尝试定义一个接口,该接口的函数只接受实现它的类类型。这是我目前所拥有的:
public interface ICombinableAction : IAction {
public bool CombineActions(ICombinableAction toCombine);
}
public class MoveAllObjects : ICombinableAction {
public bool CombineActions(ICombinableAction toCombine) {
if (!(toCombine is MoveAllObjects)) {
// This isn't possible, inform the caller
return false;
}
... // Combining logic
return true;
}
}
不幸的是,由于函数无法在编译时检查传入的对象的类型,我必须处理使用不兼容类的情况,然后在调用者中处理。
理想情况下,这可以通过定义接口来实现,使得只有同一个类的实例是可能的,类似于:
public interface ICombinableAction : IAction {
public void CombineActions(Implementor toCombine);
}
public class MoveAllObjects : ICombinableAction {
public void CombineActions(MoveAllObjects toCombine) {
... // Combining logic
}
}
我怀疑这是不可能的,因为C# Interfaces: Is it possible to refer to the type that implements the interface within the interface itself? 中的答案。我怀疑这个问题Why C# doesn't allow inheritance of return type when implementing an Interface 也在绕开与我相同的问题。不过,这两个问题都没有帮助我找到针对我的特定问题的解决方案。
在这种情况下,什么是好的解决方案?
【问题讨论】: