我希望将班级中的各个属性标记为脏。
我在这里遇到了一种将整个类标记为脏的方法。这可以简化为。
class DirtyClass
{
private string bar;
private int foo;
public string Bar
{
get { return bar; }
set { SetProperty(ref bar, value); }
}
public int Foo
{
get { return foo; }
set { SetProperty(ref foo, value); }
}
public bool IsDirty { get; private set; }
protected void SetProperty<T>(ref T field, T value)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
IsDirty = true;
}
}
}
我尝试使用此代码作为创建 DirtyProperty 类的指南
class DirtyProperty<T> where T : class
{
private bool isDirty = true;
private T property;
public bool GetIsDirty()
{
bool b = isDirty;
// Reset dirty flag
isDirty = false;
return b;
}
public T GetValue()
{
return property;
}
public void SetValue(ref T value)
{
if (!EqualityComparer<T>.Default.Equals(property, value))
{
property = value;
isDirty = true;
}
}
}
脏标志在 GetIsDirty 方法中被标记为 false,因为它每帧只调用一次,并且不会被包含 DirtyProperty 类的类之外的其他类调用。是否有更好的方法将 isDirty 标记为 false 以处理对该函数的多次调用?
问题是,如果我使用非引用类型(例如 int),那么这种方法就会失败。
class ClassWithDirtyProperties
{
public DirtyProperty<string> Bar;
public DirtyProperty<int> Foo;
}
如何改进我的方法并解决此问题?
我希望如何使用上述类的示例
var c = new ClassWithDirtyProperties();
c.Foo.SetValue(21);
……
if (c.Foo.GetIsDirty())
{
// Update parameter
SetParameter(c.Foo.GetValue());
}