3

我有一个由一组对象实现的接口。我希望集合中的所有对象都实现一种MemberWiseCompare(ImplementingType rhs)方法,该方法要求它们使用自己的类型作为参数类型。

经过一番研究,我似乎可以改变我的界面:

  public interface IMyInterface

 public interface IMyInterface<T>

然后T用作该MemeberWiseCompare方法的参数类型。但是,我希望有一个替代解决方案,因为这会产生 200 个编译器错误,因此需要做很多工作。另外我认为这可能会导致一些问题,因为有些地方我IMyInterface用作返回或参数类型,我确信将所有这些更改为通用版本会使代码复杂化。有没有其他方法可以做到这一点?有没有更好的选择?

4

1 回答 1

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);
    }
}
于 2013-05-22T20:07:41.527 回答