由接口指定的属性的多态性

polymorphism for properties specified by interfaces(由接口指定的属性的多态性)
本文介绍了由接口指定的属性的多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不起作用?

 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 类型的 Options 属性.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).

对于它的价值,Microsoft Connect 上还有一个专门针对返回类型协方差的语言功能请求:

For what it's worth, there's also a language feature request on Microsoft Connect specifically for return type covariance:

需要 C#/所有 .NET 语言中的协变返回类型

如果您查看该页面,他们还提到常见的解决方法是使用显式接口实现:

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

这篇关于由接口指定的属性的多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)