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

C# 强制实现类使用自己的类型作为方法参数的类型,c#,.net,oop,generics,C#,.net,Oop,Generics,我有一个由一组对象实现的接口。我希望集合中的所有对象都实现MemberWiseCompare(implementingtyperhs)方法,该方法要求它们使用自己的类型作为参数类型 经过一点研究,我似乎可以改变我的界面,像 public interface IMyInterface 到 公共接口IMyInterface 然后使用T作为MemeberWiseCompare方法的参数类型。然而,我希望有一个替代的解决方案,因为这会产生大约200个编译器错误,因此需要做大量的工作。此外,我认为

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

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

  public interface IMyInterface

公共接口IMyInterface

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

我假设您的界面当前看起来像:

public interface IMyInterface
{
    bool MemberwiseCompare(object other);
}
在这种情况下,您可以将其更改为:

public interface IMyInterface
{
    bool MemberwiseCompare<T>(T other) where T : IMyInterface;
}

泛型是一种方法。C#中有“奇怪的重复模板模式”。但还是要给它一个回顾。对于返回现在的非泛型接口的现有方法,可以将此版本作为泛型版本的基础,不需要泛型的代码仍然可以工作。哪种编译器错误?做
公共接口IMyInterface:IMyInterface
作为中间步骤会有帮助吗?这不是有用的地方吗?如果是这样的话,不幸的是在C#中没有,这更符合我的要求。我将把这个问题留一段时间,看看是否还有其他好的建议,但我怀疑我是否能找到更合适的建议。@evanmcdonnal这可能也是我会选择的道路
public interface IMyInterface
{
    bool MemberwiseCompare<T>(T other) where T : IMyInterface;
}
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);
    }
}