用'generic'的方法创建一个接口,但是它的泛型类型是接口的实现者

Create an interface with a method that's 'generic', but it's generic type is the implementer of the interface

在 C# 中有没有什么方法可以让泛型类型始终是接口中的实现类型?像这样:

interface Foo
{
    this GetOtherThis();
}

class Bar : Foo
{
    Bar GetOtherThis();
}

是的,您可以使用通用接口编写代码:

interface Foo<T>
{
    T GetOtherThis();
}

class Bar : Foo<Bar>
{
    Bar GetOtherThis();
}

注意: 没有通用约束可以施加在 T 上以使 T 成为实施 class。 Jon Skeet 解释得更详细。

Is there any way in C# to have a generic type that is always the implementing type in an interface?

没有。目前给出的答案满足这一点,原因有二:

  • 您始终可以使用不同的 T

    实现接口
    interface IFoo<T>
    {
        T GetOtherThis();
    }
    
    public class NotAString : Foo<string>
    {
        string GetOtherThis() { ... }
    }
    

    这可以通过约束某处得到修复:interface IFoo<T> where T : IFoo<T>但这仍然不能阻止它;

    public class Good : IFoo<Good> { ... }
    
    public class Evil : IFoo<Good> { /* Mwahahahaha */ }
    
  • 无论如何继承都会破坏它:

    interface IFoo<T>
    {
        T GetOtherThis();
    }
    
    public class WellBehaved : IFoo<WellBehaved>
    {
        WellBehaved GetOtherThis() { ... }
    }
    
    public class BadlyBehaved : WellBehaved
    {
        // Ha! Now x.GetOtherThis().GetType() != x.GetType()
    }
    

基本上 C# 中没有任何东西可以为您强制执行此操作。如果您相信接口实现是明智的,那么通用接口方案仍然有用,但您需要了解它的局限性。