-1

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

我想要做的是创建一个方法来处理对_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.");
    }

}
4

1 回答 1

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

于 2017-08-18T12:31:03.480 回答