【发布时间】:2021-02-06 15:55:33
【问题描述】:
据我了解,C# 中的 setter 旨在强制执行业务逻辑并保留一些不变性。但这似乎与大多数类是可变的并且 getter 分发对它们的引用的事实不相容。假设我有一个Car 类:
class Car
{
public Car(int maxSpeed)
{
_maxSpeed = maxSpeed;
}
public void UpgradeEngine()
{
_maxSpeed += 50;
}
private int _maxSpeed;
public int max_speed
{
get => _maxSpeed;
}
}
我有一个SchoolDriver 班级,不允许拥有最高速度超过 200 的汽车:
class SchoolDriver
{
private Car _schoolBus = new Car ( 200 );
public Car SchoolBus
{
get => _schoolBus;
set
{
if (value.max_speed <= 200)
_schoolBus = value;
}
}
}
当然,您不能分配不符合要求的新车,但您可以轻松更改现有汽车的最大速度:
class Program
{
public static int Main()
{
SchoolDriver d = new SchoolDriver();
d.SchoolBus = new Car(250); // Won't change the car.
d.SchoolBus.UpgradeEngine(); // Will change the speed
return 0;
}
}
这似乎打破了不变量和封装。除了将Car 类包装在不可变类中之外,很难强制执行任何类型的不变量。
我的问题:对于具有可变对象和引用语义的 setter,什么是有效用例?如何强制执行诸如“SchoolDriver 的汽车不能超过 200 最大速度”之类的内容?
在 C++ 中,我会返回一个 const-refence,它(语义上)不能在没有邪恶的情况下被静音 const_cast。
【问题讨论】:
标签: c#