从接口继承的方法可以返回接口中的另一种类型吗?

时间:2015-02-13 15:39:35

标签: c# polymorphism

假设我有这样的代码:

interface IObject
{
     IObject GetSomeObject();
}

public class ObjectClass : IObject
{
     IObject GetSomeObject()
     {
     // method implementation here
     }
}

有没有办法,我使GetSomeObject()ObjectClass方法返回ObjectClass,没有IObject

我知道我可以这样使用它:

ObjectClass object1= someObject1.GetSomeObject() as ObjectClass;

但我想要达到的目标是:

public class ObjectClass : IObject
{
     ObjectClass GetSomeObject()
     {
     // method implementation here
     }
}     

这样可能吗?

3 个答案:

答案 0 :(得分:6)

您可以使用泛型:

interface IObject<T> where T : IObject<T>
{
    T GetSomeObject();
}

public class ObjectClass : IObject<ObjectClass> { ... }

答案 1 :(得分:4)

您可以使用explicit interface implementation

public interface IObject
{
     IObject GetSomeObject();
}

public class ObjectClass : IObject
{
    public ObjectClass GetSomeObject()
    {
        return this;
    }

    IObject IObject.GetSomeObject()
    {
        return this;
    }
}

这样,访问ObjectClass的消费者可以呼叫ObjectClass GetSomeObject(),而通过IObject访问此类实例的消费者只能呼叫IObject GetSomeObject()

答案 2 :(得分:1)

您可以使用泛型:

interface IObjectReturnable<T>
{
    T GetSomeObject();
}

public class ObjectClassRet : IObjectReturnable<ObjectClassRet>
{
    public ObjectClassRet GetSomeObject()
    {
        // method implementation here
        return new ObjectClassRet();
    }
}