返回派生类而不是接口

时间:2016-03-15 22:44:44

标签: c#

是否可以在C#中的接口定义中返回派生类? 某种返回型协方差。

例如:

public interface IAnimal
{
    this GetAnimal();
}

public class Dog : IAnimal
{
    Dog GetAnimal() { return new Dog(); }
}

3 个答案:

答案 0 :(得分:2)

  

是否可以在接口定义中返回派生类   在C#?

是的,如果您定义了通用接口。

public interface IAnimal<T>
{
    T GetAnimal();
}

public class Dog : IAnimal<Dog>
{
    public Dog GetAnimal() { return new Dog(); }
}

您可以继续阅读here

答案 1 :(得分:1)

当然,如果将派生类作为类型约束传递:)

public interface IAnimal<T>
{
    T GetAnimal();
}

public class Dog : IAnimal<Dog>
{
    public Dog GetAnimal() { return new Dog(); }
}

答案 2 :(得分:1)

C#不支持返回类型协方差,至少从C#6开始。它在Roslyn GitHub上是very commonly requested feature,并且早在Roslyn存在之前就已存在。

Eric Lippert在他的answer写道:

  

该功能未实现,因为此处没有人实现它。必要但不充分的要求是功能的好处超过其成本。

     

成本相当可观。该运行时本身不支持该功能,它直接针对我们使C#版本化的目标,因为它引入了另一种形式的脆弱基类问题。

所以请坐下,紧紧握住,然后用手指交叉C#7/8/9。但是不要过多地抱你的希望 - 正如所说的那样,这是一个高成本的低效益功能,可能需要修改CLR。

目前,请查看Christos' answer

相关问题