c# - 覆盖接口(interface)的返回类型

标签 c# class inheritance interface polymorphism

希望这可以做到!

我有一个基础接口(interface)

interface IEntity
{
    IConfiguration Configuration {get; set;}
}

还有一个抽象类

abstract class Entity
{
    abstract IConfiguration Configuration {get; set;}
}

下面介绍一个继承自“Entity”的“Client”

interface Client : Entity
{

}

客户端有一个“Configuration”的子类

interface IClientConfiguration : IConfiguration
{

}

最后,我希望我的 Client 类看起来像这样

class Client : IClient
{
    public IClientConfiguration Configuration {get; set;}
}

问题是,C# 提示我没有为类 Client 返回 IConfiguration。我可以通过声明新的公共(public) IClientConfiguration 来覆盖它...但在我走那条路之前,我想知道是否有更好的方法来构建它并保持最佳实践。

感谢您的帮助! --迈克尔

最佳答案

你可以使用 explicit interface implementation在您的客户类中:

class Client : IClient
{
    public IClientConfiguration Configuration { get; set; }

    // Explicit implementation
    IConfiguration IEntity.Configuration 
    { 
        get { return this.Configuration; }
        set { /* what to do here? */ }
    }
}

这是实现 IEnumerable<T> 时的常见做法因为该接口(interface)扩展了 IEnumerable .这两个接口(interface)都声明了一个名为 GetEnumerator 的方法但具有不同的返回类型( IEnumerator<T>IEnumerator )。

但是,我认为您在某个地方犯了设计错误。配置属性是get/set。这给人的印象是您的 Client 类必须能够接受任何类型的配置。同时,您的 Client 类似乎只适用于 IClientConfiguration值。令人困惑。

关于c# - 覆盖接口(interface)的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34643741/

相关文章:

class - 项目管理器包的 Atom 编辑器图标类是什么?

c++ - 遗产。如何让 child = parent

java - 访问不同包中的继承子类

c# - 任务的 OnCompleted 回调在哪里?

android - 我的应用程序在最初启动到设备时加载,但在我退出应用程序并返回后,它甚至不会尝试启动

c# - Linq 表达式 : Left Join Duplicating Rows

python - 为什么在 sklearn GridsearchCV SVM 中使用 class_weight 时会出现错误?

c# - 每个派生类的 Web API 方法还是只有一种方法可以服务于所有类?

c# - StackExchange.Redis 阻塞弹出设计

c# - 如果不是启动项目,如何在 C++ 应用程序中打断点