【问题标题】:C# - Interface generic method constraint to match derived typeC# - 接口泛型方法约束以匹配派生类型
【发布时间】:2017-09-05 07:56:55
【问题描述】:

假设我有一个接口 IA,其中包含一个名为 Foo 的通用方法。

public interface IA {
    int Foo<T>(T otherType);
}

我希望 T 与派生类的类型相同:

class A : IA {
    int Foo(A otherType)
    {
    }
}

我尝试了以下(语法错误):

public interface IA {
    int Foo<T>(T otherType) where T : this;
}

我的约束需要如何实现?

【问题讨论】:

  • 不要认为那是可能的。接口不知道什么会实现它。这基本上是鸡/蛋的事情。

标签: c# generics inheritance interface constraints


【解决方案1】:

你必须这样做:

public interface IA<T>
{
    int Foo(T otherType);
}

class A : IA<A>
{
    public int Foo(A otherType)
    {
        return 42;
    }
}

这是强制接口成员的泛型类型的唯一方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多