我有一组对象实现的接口。我希望集合中的所有对象都实现一个MemberWiseCompare(ImplementingType rhs)
方法,该方法要求他们使用自己的类型作为参数类型。
经过一番研究后,似乎我可以改变我的界面;
public interface IMyInterface
到
public interface IMyInterface<T>
然后使用T
作为MemeberWiseCompare
方法的参数类型。但是,我希望有一个替代解决方案,因为这会产生200个编译器错误,因此需要做很多工作。另外我认为它可能会导致一些问题,因为有些地方我使用IMyInterface
作为返回或参数类型,我确信将所有这些更改为泛型版本会使代码复杂化。有没有其他方法可以做到这一点?还有更好的选择吗?
答案 0 :(得分:5)
我认为你的界面目前看起来像是:
public interface IMyInterface
{
bool MemberwiseCompare(object other);
}
在这种情况下,您可以将其更改为:
public interface IMyInterface
{
bool MemberwiseCompare<T>(T other) where T : IMyInterface;
}
这使接口保持非通用性,但在传递调用MemberwiseCompare
时为您提供了一些额外的类型安全性。实现不需要改变(除了它们的签名),因为它们当前将不得不进行运行时类型检查。我假设由于泛型参数的类型推断,大多数调用站点都不需要更改。
编辑:另一种可能性是您可以添加通用IMyInterface<T>
接口,并让您的实现类实现两个接口(一个需要显式实现)。然后,您可以逐渐转到通用接口,同时废弃非通用版本,例如
public class MyClass : IMyInterface, IMyInterface<MyClass>
{
public bool MemberwiseCompare(MyClass other) { ... }
bool IMyInterface.MemberwiseCompare(object other)
{
MyClass mc = other as MyClass;
return mc != null && this.MemberwiseCompare(mc);
}
}