2013-05-14 104 views
0

我有一个定义的接口iClass。接口中的一种方法将另一个接口iObject作为参数。在另一个接口的实现中调用接口的特定子孙

iClass的一个具体实现中,我需要一个具体实现iObject,ObjectImplementation的方法 - 但C#告诉我需要按原样实现该方法。

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

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 
    { 

    } 
} 

回答

2

该合同明确指出该方法需要iObjectObjectImplementation一个类实现此接口。但也可能有其他人。 iClass合同规定全部这些实现是有效的参数。

如果你真的需要使用一个通用的接口,考虑到参数限制为ObjectImplementation

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

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

    } 
} 
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; 
    } 
} 
+0

这如果'ClassImplementation'中的'SomeMethod'的实现确实需要一个'ObjectImplementation'而不需要其他东西,那么这个方法将不起作用。例如。因为'ObjectImplementation'具有额外的成员。 – 2013-05-14 07:32:54