继承接口作为返回类型 - 无法转换表达式

时间:2013-12-13 21:49:41

标签: c# inheritance interface

我有以下

public interface IAwesomeInterface
{
    string Prop1 {get; set;}
    string Prop2 {get; set;}

    List<SomeObject> GetObjects();
}

public abstract class AbstractObject : IAwesomeInterface 
{
    public string Prop1 {get; set;}
    public string Prop2 {get; set;}

    public abstract List<SomeObject> GetObjects();

}

public class ConcreteObject1 : AbstractObject
{
    public List<SomeObject> GetObjects()
    {
        return new List<SomeObject>();
    }
}

public class ConcreteObject2 : AbstractObject
{
    public List<SomeObject> GetObject()
    {
        //do some other stuff
        return new List<SomeObject>();
    }
}

和实施:

public class ObjectFactory
{

    public IAwesomeInterface GetObject()
    {

        return new ConcreteObject1();
    }
}

我收到错误“无法将表达式类型ConcreteObject1转换为返回类型IAwesomeInterface”

由于ConcreteObject1继承自AbstractObject,这是否意味着它实现了IAwesomeInterface并且应该是可接受的返回值?

1 个答案:

答案 0 :(得分:6)

您的代码也会抛出另一个错误,这就是存在第二个错误的原因:

  

'ConcreteObject1'没有实现继承的抽象成员'AbstractObject.GetObjects()'

修复此问题,你引用的那个也会消失。为此,请在overrideGetObjects()中的ConcreteObject1方法旁边添加ConcreteObject2

public class ConcreteObject1 : AbstractObject
{
    public override List<SomeObject> GetObjects()
    {
        return new List<SomeObject>();
    }
}

public class ConcreteObject2 : AbstractObject
{
    public override List<SomeObject> GetObjects()
    {
        //do some other stuff
        return new List<SomeObject>();
    }
}

PS。您的代码在GetObjects方法名称中有拼写错误。您在方法名称末尾错过了s