检查对象是否更改的最佳做法是什么?

pen*_*ake 23 .net c#

我需要知道如何检查对象是否已更改.基本上我需要像名为TrackChanges的属性,当我将其设置为true一次并且如果此对象中的任何数据被"更改"时,同一对象(IsObjectChanged)上的方法可以返回true.

你有没有需要这样的东西,你是如何解决它的?如果已经有这种情况的最佳实践,我不想发明轮子?

我想在我的setter中调用TrackChange = true之前克隆该对象.当我调用IsObjectChanged()时,通过使用反射,我将比较它的所有公共字段值和克隆的副本.我不确定这是不是一个好方法.

有什么建议吗?

谢谢,burak ozdogan

sti*_*k81 16

当我需要跟踪对象的属性更改以进行测试时,我在对象PropertyChanged事件上挂钩了一个事件处理程序.这对你有帮助吗?然后,您的测试可以根据更改执行他们想要的任何操作.通常我会计算更改次数,并将更改添加到词典等.

要实现此目的,您的类必须实现INotifyPropertyChanged接口.然后任何人都可以附加和收听已更改的属性:

public class MyClass : INotifyPropertyChanged { ... }

[TestFixture]
public class MyTestClass
{
    private readonly Dictionary<string, int> _propertiesChanged = new Dictionary<string, int>();
    private int _eventCounter; 

    [Test]
    public void SomeTest()
    {
        // First attach to the object
        var myObj = new MyClass(); 
        myObj.PropertyChanged += SomeCustomEventHandler;
        myObj.DoSomething(); 
        // And here you can check whether the object updated properties - and which - 
        // dependent on what you do in SomeCustomEventHandler. 

        // E.g. that there are 2 changes - properties Id and Name changed once each: 
        Assert.AreEqual(2, _eventCounter); 
        Assert.AreEqual(1, _propertiesChanged["Id"]);
        Assert.AreEqual(1, _propertiesChanged["Name"]);
    }

    // In this example - counting total number of changes - and count pr property. 
    // Do whatever suits you. 
    private void SomeCustomEventHandler(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        var property = e.PropertyName;
        if (_propertiesChanged.ContainsKey(property))
            _propertiesChanged[property]++;
        else
            _propertiesChanged[property] = 1;

        _eventCounter++;
    }
}
Run Code Online (Sandbox Code Playgroud)