在接口方法上,可以使用泛型类型参数。被约束为类型实现接口?

时间:2015-10-08 23:59:12

标签: c# generics types interface constraints

我想知道是否可以在C#中完成以下操作,但如果您知道备用的.NET路径(F#,VB等),我也希望听到它。

在接口(或抽象类)中,在泛型方法上,我希望将方法的泛型类型参数约束到实现接口的具体类。

在伪代码中,界面可能如下所示:

interface Interface1<T> 
    where typeof(T) == this.GetType() //Illegal
{
    T Friend<T>();
}

下一个变体会发出警告,“类型参数'T'与外部类型'Interface2'中的类型参数同名”

interface Interface2<T>
    where T : Interface2<T>
{
    T Friend<T>(); //The second 'T' will have the green warning underline.
}

这个伪代码的语义定义了一个比我真正想要的限制更少的约束。实现Interface1的类必须将自己用作类型参数,

class Class1 : Interface1<Class1> //Legal
class Class2 : Interface1<Class1> //Constraint violation

虽然实现Interface2的类可以使用任何实现Interface2的类作为类型参数。

class Class1 : Interface2<Class1> //Ok
class Class2 : Interface2<Class1> //Ok

实现类可能如下所示:

class Robot: Interface2<Robot> 
{
    private Robot friend;

    Robot Friend<Robot>() {
        return friend;
    }
}

此类将抛出编译器错误“无法将类型'MyNamespace.Robot'隐式转换为'Robot'”,但如果您符合这样的类型名称:

class Robot: Interface2<Robot> 
{
    private MyNamespace.Robot friend;

    MyNamespace.Robot Friend<Robot>() {
        return friend;
    }
}

它将更改为“'MyNamespace.Robot'未实现接口成员'MyNamespace.Interface2.Friend()'。'MyNamespace.Robot.Friend()'无法实现'MyNamespace.Interface2.Friend()',因为它没有匹配的返回类型'T'。“

有没有办法制作Interface1?我忽略了任何反射魔法?

1 个答案:

答案 0 :(得分:1)

以下作品:

interface Interface2<T> where T : Interface2<T>
{
    T Friend();
}

class Robot : Interface2<Robot>
{
    private Robot friend;

    public Robot Friend()
    {
        return friend;
    }
}

没有必要将通用类型放在Friend方法上。

另外,不幸的是,据我所知,没有办法制作Interface1

相关问题