如何清晰地管理具有多个接口的类和组件?

huangapple go评论62阅读模式
英文:

How to cleanly manage classes and components with multiple interfaces?

问题

我有一辆汽车,它是一个ICar,一个IFuelPowered,以及一个IVehicle

我的汽车包含一个CarData类,它是一个ICarData,一个IFuelPoweredData,以及一个IVehicleData

虽然Car类包含行为逻辑,数据接口提供了各种属性,例如:

ICarData:

  • 品牌

IFuelPoweredData:

  • 油箱容量

IVehicleData:

  • 最大速度

在Car类中,我想将仅ICarData作为属性包含(它继承自IFuelPoweredData和IVehicleData接口,因此符合所有这些合同)

但是我必须这样做:

IVehicleData IVehicle.Data => Data;
IFuelPoweredData IFuelPowered.Data => Data;
public ICarData Data { get; }

否则编译器会抱怨IFuelPowered和IVehicle上的接口未实现。这是因为例如,IFuelPowered在其接口上有IFuelPoweredData。

这让我感到困惑,因为Car确实有一个ICarData属性(它本身实现了IFuelPoweredData和IVehicleData)。是否有更清晰的方法来处理这种问题的样式?

英文:

I have a Car which is an ICar, an IFuelPowered and an IVehicle

My Car contains a CarData class, which is an ICarData, an IFuelPoweredData, and an IVehicleData

Whilst the Car class holds behaviour logic, the data interfaces present various properties, for example:

ICarData:

  • Brand

IFuelPoweredData:

  • TankSize

IVehicleData

  • MaxSpeed

Within the Car class, I'd like to include only ICarData as a property (which inherits from the IFuelPoweredData and IVehicleData interfaces, and therefore complies with all these contracts)

But instead I have to do this:

IVehicleData IVehicle.Data => Data;
IFuelPoweredData IFuelPowered.Data => Data;
public ICarData Data { get; }

Else the compiler complains the interfaces on IFuelPowered and IVehicle are not implemented. This is because for example, IFuelPowered has IFuelPoweredData on its interface.

This confuses me because Car does have a property of ICarData (which itself implements IFuelPoweredData and IVehicleData).

Is there a cleaner approach to this style of problem?

答案1

得分: 1

你只需在ICarData中实现IFuelPoweredDataIVehicleData

{
    //接口的内容
}```

然后,在你的```Car```类中,只需要一个```ICarData```属性。

<details>
<summary>英文:</summary>

You can just implement ```IFuelPoweredData``` and ```IVehicleData``` in ```ICarData```.

    public interface ICarData : IFuelPoweredData, IVehicleData
    {
    	//Contents of interface
    }

The you will only need an ```ICarData``` property in your ```Car``` class.

</details>



huangapple
  • 本文由 发表于 2023年2月8日 19:53:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定