多态性通过接口指定的属性 [英] polymorphism for properties specified by interfaces
问题描述
为什么犯规这项工作?
Why doesnt this work?
public class ClassOptions {}
public interface Inode {
ClassOptions Options {get;}
}
public class MyClass : Inode {
public ClassOptions Options { get; set; }
}
public class ClassDerivedOptions : ClassOptions {
}
public class MyDerivedClass : Inode {
public ClassDerivedOptions Options { get; set; } << does not implement INode...
}
[编译器的消息告诉我,为什么它打破但我想知道为什么后面编译犯规让这个通过推理 - 也是,如果有任何变通? - 谢谢]
[ the compiler message tells me why it breaks but i'd like to know the reasoning behind why the compiler doesnt let this through - also if there are any work arounds? - thanks]
推荐答案
它不起作用,因为inode的界面明确要求类型ClassOptions的选项属性。 C#不支持返回类型的协方差(这是你在这种情况下,要求的东西)。
It doesn't work because the INode interface explicitly calls for an Options property of type ClassOptions. C# doesn't support return type covariance (which is what you're asking for in this case).
有关它的价值,但也对微软的语言功能要求专为连接返回类型的协方差:
For what it's worth, there's also a language feature request on Microsoft Connect specifically for return type covariance:
如果你看网页,他们还提到了共同的解决办法是使用显式接口实现:
If you look at the page, they also mention that the common work-around is to use Explicit Interface Implementation:
public class MyDerivedClass : INode
{
public ClassDerivedOptions Options { get; set; }
public ClassOptions INode.Options { get { return Options; } }
}
这篇关于多态性通过接口指定的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!