.net C#用具有数百个属性的类管理IsDirty功能的通用方法

本文关键字:属性 管理 功能 方法 百个 IsDirty net | 更新日期: 2023-09-27 17:59:01

我有一个复杂的类,至少有100个属性。我想跟踪自类加载数据(初始化)以来是否有任何属性发生了更改,所以我编写了以下代码来管理它。如果传入的值与属性的当前值相同,我也不想设置IsDirty标志。当类被实例化时,IsDirty标志被设置为false,当数据被加载到类中时,IsInitializing标志将被设置为true。

private T SetPropertyValue<T>(T property, T value)
{
if  (!property.Equals(value))
{
// If values are different, return the new value and
// if the IsInitializing flag is false, then set the dirty flag for the class.
if (!IsInitializing)
IsDirty = true;
return value;
}
// If the current value of the property and the value passed in are the same,
// return the current value of the property.
return property;
}
private DateTimeOffset? _actualProjectCompletionDate;
public DateTimeOffset? ActualProjectCompletionDate
{
get
    {
        return _actualProjectCompletionDate;
    }
set
    {
        _actualProjectCompletionDate = SetPropertyValue(_actualProjectCompletionDate, value);
    }
}

我想避免在set方法中两次指定实际的私有变量,但当我尝试使用方法而不是函数时,我必须使用out参数修饰符,并且我还必须用default(T)初始化属性值,这当然否定了我想要做的事情。我认为以上方法会起作用,我只是想知道是否有更好的方法。

.net C#用具有数百个属性的类管理IsDirty功能的通用方法

使用ref关键字:

private T SetPropertyValue<T>(ref T property, T value)
{
    if (!EqualityComparer<T>.Default.Equals(property, value))
    {
        if (!IsInitializing)
        {
            IsDirty = true;
        }
        property = value;
    }
}
public DateTimeOffset? ActualProjectCompletionDate
{
    get { return _actualProjectCompletionDate; }
    set { SetPropertyValue(ref _actualProjectCompletionDate, value); }
}