首页 > 解决方案 > 分配最后一个属性时引发事件

问题描述

当最后一个属性分配给对象时,有没有办法运行事件?我不想在每次属性值更改时使用 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;

编辑: 我没有设置一定数量的属性来考虑对象“完整”。问题是我需要对已设置的属性进行一些计算,但我不想在每次更改属性时都重复计算。创建对象的时间重复计算没有问题。但是在执行时,应用程序将“一次”改变很多属性,比如数百次,所以我想尽可能少地进行这些计算。

标签: c#

解决方案


假设您想在设置PropertiesSet()了所有必需的属性后调用方法。如果这是最后一个属性,您必须检查属性的set()方法,如果是,则启动计算。为简单起见,我建议使用可空类型并检查 null 以确定是否设置了最后一个属性。

下面的示例代码使用三个必需属性Blocks和一个非必需属性。ColourTitleLayers

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;

推荐阅读