强制实现类使用它们自己的类型作为方法参数的类型

本文关键字:类型 方法 参数 自己的 实现 | 更新日期: 2023-09-27 18:14:48

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

经过一番研究,我似乎可以把我的界面从;

  public interface IMyInterface

 public interface IMyInterface<T>

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

强制实现类使用它们自己的类型作为方法参数的类型

我假设你的界面目前看起来像:

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);
    }
}