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

Alp*_*der 0 c# generics interface

在C#中是否有任何方法可以使用通用类型,它始终是接口中的实现类型?像这样的东西:

interface Foo
{
    this GetOtherThis();
}

class Bar : Foo
{
    Bar GetOtherThis();
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

在C#中是否有任何方法可以使用通用类型,它始终是接口中的实现类型?

不会.到目前为止给出的答案不满足这个要求,原因有两个:

  • 您始终可以使用不同的接口实现接口 T

    interface IFoo<T>
    {
        T GetOtherThis();
    }
    
    public class NotAString : Foo<string>
    {
        string GetOtherThis() { ... }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    这可以通过约束在某处修复:interface IFoo<T> where T : IFoo<T>但这仍然不能阻止这种情况;

    public class Good : IFoo<Good> { ... }
    
    public class Evil : IFoo<Good> { /* Mwahahahaha */ }
    
    Run Code Online (Sandbox Code Playgroud)
  • 无论如何继承都会破坏它:

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

基本上C#中没有任何内容可以为你强制执行.如果您认为接口实现是合理的,那么通用接口方案仍然有用,但您需要了解其局限性.