为什么我不能这样做?
IHasOperatingSystem {
IOperatingSystem OperatingSystem { get; }
}
Computer<T> : IHasOperatingSystem where T : IOperatingSystem {
public T OperatingSystem { get; }
}
它告诉我类型应该是 IOperatingSystem,但是如果 T 实现了 IOperatingSystem,那还不够吗?
另外,我意识到这个问题的标题可能有点令人困惑,但我想不出更好的表达方式。
最佳答案
It's telling me that the type should be IOperatingSystem, but if T implements IOperatingSystem, shouldn't that be sufficient?
不,这不是 C# 的工作方式。为了实现接口(interface)或重写方法,参数类型和返回类型必须完全匹配。从 C# 5 规范的第 13.4.4 节:
For purposes of interface mapping, a class member A matches an interface member B when:
- A and B are methods, and the name, type, and formal parameter lists of A and B are identical.
- ...
(这里的“类型”应该读作“返回类型”。)
现在你可以让你的
IHasOperatingSystem
类型泛型,当然:public interface IHasOperatingSystem<T> where T : IOperatingSystem
{
T OperatingSystem { get; }
}
public class Computer<T> : IHasOperatingSystem<T> where T : IOperatingSystem
{
public T OperatingSystem { get { ... } }
}
或者,您可以在
Computer<T>
中使用显式接口(interface)实现。类(class):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 { ... } };
}
关于c# - 使用实现所需返回类型的返回类型实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24789373/