2

我正在遍历 C# 类的属性以将值与另一个实例进行比较。这个概念似乎很简单,并且适用于我正在尝试做的事情。但是,我的 foreach 循环永远不会停止。它只是继续循环遍历类并产生一个StackOverflowException. 我对这个不知所措。任何帮助将不胜感激!

public static Object ORIGINALRECORD { get; set; }

protected String DirtySets() 
{
    String sDirtySets = "";

    foreach (PropertyInfo property in this.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
    {
        if (ORIGINALRECORD.GetType() == this.GetType())
        {
            System.Diagnostics.Debug.WriteLine(property.Name);
            object originalValue = ORIGINALRECORD.GetType().GetProperty(property.Name).GetValue(ORIGINALRECORD, null);
            object newValue = property.GetValue(this, null);
            if (!object.Equals(originalValue, newValue))
            {
                sDirtySets = (sDirtySets == "" ? "" : sDirtySets + ",") + property.Name + "=?";
            }    
        }
    }

    return "SET "+sDirtySets;
}
4

1 回答 1

3

在循环内部,您有一个语句,用于检索类上的属性值:

object newValue = property.GetValue(this, null);

只要对象的类型不一样,ORIGINALRECORD就检索所有公共属性值的类型。

如果其中一个属性的 getter 调用DirtySets您将获得无限递归。在你回调的循环内部DirtySets开始一个新的循环,依此类推,直到你得到一个StackOverflowException.

为避免这种情况,您需要确保DirtySets不从任何公共属性的 getter 调用,或者不检索DirtySets在 getter 中调用的属性的值。

于 2013-07-19T13:06:50.293 回答