c# - 分配最后一个属性时引发事件
问题描述
当最后一个属性分配给对象时,有没有办法运行事件?我不想在每次属性值更改时使用 INotifyPropertyChanged 来触发事件。我希望仅在分配最后一个属性时
触发事件或方法。
例如这里的事件在分配颜色时被触发
Model model = new Model();
model.Blocks = 2;
model.Layers = 3;
ModelManager manager = new ModelManager();
manager.Models.Add(model);
model.Color = Color.Blue;
在这里分配图层时会触发该事件
Model model = new Model();
model.Blocks = 2;
ModelManager manager = new ModelManager();
manager.Models.Add(model);
model.Color = Color.Blue;
model.Layers = 3;
编辑: 我没有设置一定数量的属性来考虑对象“完整”。问题是我需要对已设置的属性进行一些计算,但我不想在每次更改属性时都重复计算。创建对象的时间重复计算没有问题。但是在执行时,应用程序将“一次”改变很多属性,比如数百次,所以我想尽可能少地进行这些计算。
解决方案
假设您想在设置PropertiesSet()
了所有必需的属性后调用方法。如果这是最后一个属性,您必须检查属性的set()
方法,如果是,则启动计算。为简单起见,我建议使用可空类型并检查 null 以确定是否设置了最后一个属性。
下面的示例代码使用三个必需属性Blocks
和一个非必需属性。Colour
Title
Layers
public class Model
{
private int? blocks = null;
private Color? colour = null;
private string title = null;
public int? Blocks
{
get { return blocks; }
set { blocks = value; PropertiesSet(); }
}
public Color? Colour
{
get { return colour; }
set { colour = value; PropertiesSet(); }
}
public string Title
{
get { return title; }
set { title = value; PropertiesSet(); }
}
public int Layers // not required property
{ get; set; }
private void PropertiesSet()
{
if (blocks is null || colour is null || title is null) return;
// Add the calculations here
}
}
中止条件PropertiesSet()
可能比仅检查null
. 例如,您可能想要检查 0Blocks
和/或空字符串Title
,但您可以在分配属性时拒绝此类非法值。
您可以从中删除条件检查PropertiesSet()
并将其放在单独的方法中,例如:
private bool AllSet() => blocks is not null && colour is not null && title is not null;
推荐阅读
- java - 等待设备时出错:AVD Nexus_5_API_25 的模拟器进程被杀死
- symfony - Symfony EasyAdminBundle v1.17.14:如何不在表单的子类中显示属性
- ansible - 为什么 Ansible 将列表转换为字符串?
- javascript - 带有 KmlLayer 的 Google 地图 API
- javascript - 比较来自 API 的两个响应但出现错误
- reactjs - 使用打字稿时方法反应getDerivedStateFromProps问题
- javascript - 如何将 POST(javascript) 发送到 laravel 刀片文件?
- oracle - 使用 Oracle 应用程序警报插入表
- javascript - iOS Swift 上的 javascript 需要等到通过 XMLHttpRequest 加载动态内容
- python - Python - 烧瓶 BadRequestKeyError:400 错误请求:KeyError