简体   繁体   English

覆盖接口的返回类型

[英]Overriding an interface's return type

here's hoping this can be done! 希望可以做到!

I have an base interface 我有一个基本界面

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

And an abstract class 还有一个抽象类

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

Now I'll introduce a "Client" that inherits from "Entity" 现在,我将介绍一个继承自“实体”的“客户端”

interface Client : Entity
{

}

Clients have a child class of "Configuration" 客户端的子类为“配置”

interface IClientConfiguration : IConfiguration
{

}

So lastly, I'd like my Client class to look like this 最后,我希望我的Client类看起来像这样

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

The problem is, C# is complaining that I'm not returning an IConfiguration for class Client. 问题是,C#抱怨我没有为Client类返回IConfiguration。 I can override this by declaring new public IClientConfiguration... but before I go that route, I'd like to know if there is a better way to structure this and maintain best practices. 我可以通过声明新的公共IClientConfiguration来重写此方法...但是在走那条路线之前,我想知道是否有更好的方法来构造它并保持最佳做法。

Thanks for any help! 谢谢你的帮助! --Michael --Michael

You could use explicit interface implementation in your Client class: 您可以在Client类中使用显式接口实现

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

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

This is common practice when implementing IEnumerable<T> since that interface extend IEnumerable . 这是实现IEnumerable <T>的常见做法,因为该接口扩展了IEnumerable Both of these interfaces declare a method called GetEnumerator but with different return types ( IEnumerator<T> vs IEnumerator ). 这两个接口都声明了一个称为GetEnumerator的方法,但具有不同的返回类型( IEnumerator<T>IEnumerator )。

However, I think you've made a design error somewhere. 但是,我认为您在某个地方犯了设计错误。 The configuration property is get/set. 配置属性为get / set。 That gives the impression that your Client class must be able to accept a configuration of any kind. 这给您的印象是您的Client类必须能够接受任何类型的配置。 At the same time it seems as if your Client class only work with IClientConfiguration values. 同时,似乎您的Client类仅使用IClientConfiguration值。 Confusing. 混乱。

I think you may have missed adding "IEntity" interface to your "Entity" class. 我认为您可能已经错过将“ IEntity”接口添加到“ Entity”类的想法了。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM