0

iClass定义了一个接口。接口中的一个方法将另一个接口 ,iObject作为参数。

在 的一个特定实现中iClass,我需要该方法采用iObject, ObjectImplementation- 但 C# 告诉我需要按原样实现该方法。

为什么是这样?不是ObjectImplementation一个实例iObject吗?我该如何解决这个问题?我尝试使用抽象类,但我陷入了同样的混乱。

public interface iClass {
    bool SomeMethod(iObject object);
}

public interface iObject {
    ... // some methods here
}

public ObjectImplementation : iObject {
    ... // some method implementations here
}

public ClassImplementation : iClass {
    public bool SomeMethod(ObjectImplementation object) // <- C# compiler yells at me
    {

    }
}
4

2 回答 2

2

The contract clearly states that the method requires an iObject. ObjectImplementation is one class implementing this interface. But there might be others. The contract of iClass states that all those implementations are valid parameters.

If you really need to constrain the parameter to ObjectImplementation consider using a generic interface:

public interface IClass<T> where T : IObject
{
    bool SomeMethod(T item);
}

public ClassImplementation : IClass<ObjectImplementation>
{
    public bool SomeMethod(ObjectImplementation item)
    {

    }
}
于 2013-05-14T07:17:17.967 回答
0

将 iObject 作为参数保留是一种方法,这也应该有效:

public interface iClass {
    bool SomeMethod(iObject obj);
}

public interface iObject {
}

public class ObjectImplementation : iObject {
}

public class ClassImplementation : iClass {
    public bool SomeMethod(iObject obj)
    {
        return false;
    }
}
于 2013-05-14T07:31:32.563 回答