为什么读取设置 属性 值会使 SettingsPropertyValue 对象变脏?

Why is reading a settings property value making a SettingsPropertyValue object dirty?

在实施自定义设置提供程序时,我注意到访问设置 属性 的值会将其 IsDirty 标志更改为 true

// Arrange
var property = new SettingsProperty("property1")
{
    PropertyType = typeof(Color),
    DefaultValue = "Green"
};

// Act
var result = new SettingsPropertyValue(property);

// Assert
Assert.That(result.IsDirty, Is.False);
Assert.That(result.PropertyValue, Is.EqualTo(Color.Green));
Assert.That(result.IsDirty, Is.False); // <-- Assertion fails

Reflector 给了我一个问题的答案,为什么 PropertyValue getter 会这样 - 它包含如下语句:

if (_Value != null && !Property.PropertyType.IsPrimitive && !(_Value is string) && !(_Value is DateTime))
{
    _UsingDefaultValue = false;
    _ChangedSinceLastSerialized = true;
    _IsDirty = true;
}

谁能解释一下这个乍一看奇怪的行为?

documentation 声明这是为了考虑访问复杂类型值时的任何潜在副作用,以及在不重新分配值的情况下改变值(例如修改项目时在列表中):

The IsDirty property is set to true under the following conditions:

  1. [...]

  2. The value contained in the SettingsPropertyValue object is accessed, and the value is not a string or a primitive type such as int, float, real, or DateTime. When the value managed by a SettingsPropertyValue object is a complex type (for example an ArrayList), there is no way for a SettingsPropertyValue object to detect when changes have been made. As a result, the SettingsPropertyValue object pessimistically assumes that a complex type is dirty once it has been accessed from the PropertyValue property.