0

我希望将班级中的各个属性标记为脏。

我在这里遇到了一种将整个类标记为脏的方法。这可以简化为。

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());
        }
4

2 回答 2

1
class DirtyProperty<T> where T : class

这一行说 T 应该是一个引用类型。如果您想允许 int 作为模板,请删除 where 部分。所以只说

class DirtyProperty<T>
于 2012-10-13T13:26:06.137 回答
0

你明白什么是行

where T : class

在你的代码中呢?

这是一个泛型类型约束,表示 T 应该是类类型,即引用类型。

如果您希望 T 为任何类型,请删除该行。

于 2012-10-13T13:36:56.217 回答