设置嵌套属性值的方法



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

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

考虑如下方法:

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在其 setter 中具有确定是否设置IsDirty的逻辑。

相关内容

  • 没有找到相关文章

最新更新