如何在C#中实现条件封装
我想知道如何在课堂上有条件地隐藏数据。 例如,假设我有一个名为 Car 的类,它具有三个字段: 发动机、仪表读数和里程。
我还有另外三个实体,分别称为:司机、机械师和乘客。 现在我想要的是:
驾驶员应该只能访问里程(而不是发动机和读表)
机械师应该只能访问发动机和里程(而不是读表)
乘客应该只能访问读表(和不是发动机和里程)
实现这个的最佳方法是什么..(不将整个逻辑基于 if else 语句)?
大家有什么想法吗?
谢谢。
I was wondering how one can conditionally hide data in class.
For instance , lets say I have a class called Car which has three fields :
Engine , MeterReading and Mileage.
I have three other entities called : Driver , Mechanic and Passenger.
Now what I want is that :
A Driver should only be able to access Mileage ( and not Engine and MeterReading)
A Mechanic should only be able to access Engine and Mileage( and not MeterReading)
A Passenger should only be able to access MeterReading ( and not Engine and Mileage )
What could be the best way to implement this ..( without basing the whole logic on if else statements ) ?
Any ideas guys ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我想到的第一个想法是让您的
Car
类实现 3 个不同的接口,每个其他类都可以使用这些接口与您的Car
类进行交互。例如,(我的名字肯定可以改进,但你应该明白这个想法),
IDriverAccess
接口可能如下所示:IMechanicAccess
接口可能如下:等等。然后,您的汽车类可以实现这些接口,但驾驶员、机械师和驾驶员的类可以实现这些接口。乘客将仅使用接口与对象交互。
The first idea that came to mind would be to have your
Car
class implement 3 different interfaces which each other class can use to interact with yourCar
class.For example, (and my names can definitely be improved upon, but you should get the idea), the
IDriverAccess
interface could be as follows:The
IMechanicAccess
interface could be as follows:And so on. Your car class can then implement these interfaces, but the classes for the driver, mechanic, & passenger will just use the interfaces to interact with the object.
我会使用显式接口实现。当对象按其类型访问时,它隐藏接口的实现。只有通过接口访问时才能访问该实现。在你的例子中:
I would use explicit interface implementation. It hides implementation of interface when object is accessed by its type. The implementation is accessible only when accessing by interface. In your example:
我将创建这些接口:
并让每个人使用该接口来访问汽车。
I would create these interfaces:
And let each person use the interface to access the car.
让Car类实现IEngine、ImaterReading等接口。
仅授予每个实体指定的接口访问权限。
假设一个驱动器仅具有 IMilage 访问权限,而机械师则具有 IMilage 和 IEngine。
make class Car implemented interfaces IEngine,ImaterReading and so.
Give each entity only specifyc interface access.
say a drive got IMilage access only, a mechanic IMilage and IEngine.