[英]Implementing an interface with a return type that implements the required return type
Why can't I do this? 我为什么不能这样做?
IHasOperatingSystem {
IOperatingSystem OperatingSystem { get; }
}
Computer<T> : IHasOperatingSystem where T : IOperatingSystem {
public T OperatingSystem { get; }
}
It's telling me that the type should be IOperatingSystem, but if T implements IOperatingSystem, shouldn't that be sufficient? 告诉我类型应该是IOperatingSystem,但是如果T实现IOperatingSystem,那还不够吗?
Also, I realize that the title to this question might be a little confusing, but I couldn't think of a better way to phrase it. 另外,我意识到这个问题的标题可能会有些混乱,但是我想不出一种更好的措词方式。
It's telling me that the type should be IOperatingSystem, but if T implements IOperatingSystem, shouldn't that be sufficient? 告诉我类型应该是IOperatingSystem,但是如果T实现IOperatingSystem,那还不够吗?
No. That's just not the way C# works. 不,那不是C#的工作方式。 In order to implement an interface, or override a method, the parameter types and the return type have to match exactly . 为了实现接口或覆盖方法,参数类型和返回类型必须完全匹配。 From section 13.4.4 of the C# 5 specification: 根据C#5规范的13.4.4节:
For purposes of interface mapping, a class member A matches an interface member B when: 为了进行接口映射,在以下情况下,类成员A与接口成员B匹配:
- A and B are methods, and the name, type, and formal parameter lists of A and B are identical. A和B是方法,并且A和B的名称,类型和形式参数列表相同。
- ... ...
(Here "type" should be read as "return type".) (此处的“类型”应理解为“返回类型”。)
Now you could make your IHasOperatingSystem
type generic, of course: 现在,您当然可以使IHasOperatingSystem
类型成为通用类型了:
public interface IHasOperatingSystem<T> where T : IOperatingSystem
{
T OperatingSystem { get; }
}
public class Computer<T> : IHasOperatingSystem<T> where T : IOperatingSystem
{
public T OperatingSystem { get { ... } }
}
Or alternatively you could use explicit interface implementation in the Computer<T>
class: 或者,您可以在Computer<T>
类中使用显式接口实现:
public interface IHasOperatingSystem
{
IOperatingSystem OperatingSystem { get; }
}
public class Computer<T> : IHasOperatingSystem where T : IOperatingSystem
{
// Explicit interface implementation...
IHasOperatingSystem.OperatingSystem IOperatingSystem
{
// Delegate to the public property
get { return OperatingSystem; }
}
public T OperatingSystem { get { ... } };
}
if T implements IOperatingSystem, shouldn't that be sufficient? 如果T实现IOperatingSystem,那还不够吗?
Even though it may be sufficient in other languages (Scala, I think), In C#, it is not. 即使在其他语言中(Scala,我认为)可能就足够了,但在C#中却不是。 Return types are invariant (except for delegate return types, which are covariant ). 返回类型是不变的(委托返回类型除外, 它们是covariant )。
A common workaround for these situations is to use generics, as such: 这些情况的常见解决方法是使用泛型,例如:
IHasOperatingSystem<T> where T: IOperatingSystem
{
T OperatingSystem { get; }
}
Computer<T> : IHasOperatingSystem <T> where T : IOperatingSystem
{
public T OperatingSystem { get; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.