Comparing 2 custom objects - C#

前端 未结 6 1484
鱼传尺愫
鱼传尺愫 2021-01-05 11:48

I need to write a generic method in the base class that would accept 2 objects as parameters and compares them for equality.

Ex:

public abstract cla         


        
6条回答
  •  庸人自扰
    2021-01-05 12:19

    Here's what I came up with using reflection. Hope it helps.

    public bool AreEqual(object obj)
        {
            bool returnVal = true;
    
            if (this.GetType() == obj.GetType())
            {
                FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
    
                foreach (FieldInfo field in fields)
                {
                    if(field.GetValue(this) != field.GetValue(obj))
                    {
                        returnVal = false;
                        break;
                    }
                }
            }
            else
                returnVal = false;
    
            return returnVal;
        }
    

提交回复
热议问题