设置嵌套属性值的方法

时间:2017-08-18 11:38:18

标签: c# mono nested-properties

我正在编写一个软件插件,要求所有代码都在一个类(或嵌套类)中......

我想要做的是创建一个方法,可以处理对我_data对象的嵌套属性的更改,并给我一个中心位置来做一些事情,比如设置一个脏标志,所以我知道保存它后来。

下面是一些说明我文件结构的代码,下面是两个伪方法,希望能让你了解我想要实现的目标。

public class SomePlugin
{
    private DataObject _data;
    private bool _dataIsDirty = false;

    private class DataObject
    {
        public GeneralSettings Settings { get; set; }
    }

    private class GeneralSettings
    {
        public string SettingOne { get; set; }
        public string SettingTwo { get; set; }
    }

    protected override void Init()
    {
        _data = new DataObject
        {
            Settings = new GeneralSettings
            {
                SettingOne = "Example value one.",
                SettingTwo = "Example value two."
            }
        }
    }

    // These are pseudo-methods illustrating what I'm trying to do.
    private void SetData<t>(T ref instanceProperty, T newValue)
    {
        if (newValue == null) throw new ArgumentNullException("newValue");
        if (instanceProperty == newValue) return;

        instanceProperty = newValue;
        _dataIsDirty = true;
    }

    private void SomeOtherMethod()
    {
        SetData(_data.Settings.SettingOne, "Updated value one.");
    }

}

1 个答案:

答案 0 :(得分:0)

考虑一种方法:

public class SomePlugin
{
    private DataObject _data;
    private bool _dataIsDirty = false;

    public bool IsDirty => _dataIsDirty || (_data?.IsDirty ?? false);

    private class DataObject
    {
        private bool _dataIsDirty = false;

        public bool IsDirty => _dataIsDirty || (Settings?.IsDirty ?? false);
        public GeneralSettings Settings { get; set; }
    }

    private class GeneralSettings
    {
        public bool IsDirty { get; set; }

        private string _settingOne;

        public string SettingOne
        {
            get { return _settingOne; }
            set
            {
                if (value != _settingOne)
                {
                    IsDirty = true;
                    _settingOne = value;
                }
            }
        }

        public string SettingTwo { get; set; } // Won't mark as dirty
    }
}

请特别注意SettingOne在其设置器中具有逻辑,以确定是否设置IsDirty