比较两个C#类实例的等同性(从XML生成)

时间:2015-06-05 11:03:10

标签: c# json xml serialization

我从xml生成了一个类(使用xsd.exe),现在我必须比较它的两个实例。生成的类是:

 [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
 [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable =    false)]
 public partial class ResultSet
 {
   private ResultSetResult[] resultField;

  [System.Xml.Serialization.XmlElementAttribute("Result")]
   public ResultSetResult[] Result
  {
      get
    {
        return this.resultField;
    }
    set
    {
        this.resultField = value;
     }
   }
 }

 [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
     public partial class ResultSetResult
  {
    private decimal latitudeField;
    private string precisionField;

  public decimal Latitude
  {
     get
    {
        return this.latitudeField;
    }
    set
    {
       this.latitudeField = value;
     }
   }

  [System.Xml.Serialization.XmlAttributeAttribute()]
  public string precision
  {
     get
     {
        return this.precisionField;
     }
     set
     {
         this.precisionField = value;
     }
    }
   }

我知道我们必须实现一个函数,但是这个类有部分类,那么如何比较特定字段的值?

我尝试使用

Public static bool PublicInstancePropertiesEqual<T>(T self, T to, params    string[] ignore) where T : class 
{
    if (self != null && to != null)
    {
        Type type = typeof(T);
        List<string> ignoreList = new List<string>(ignore);
        foreach (System.Reflection.PropertyInfo pi in   type.GetProperties(System.Reflection.BindingFlags.Public |   System.Reflection.BindingFlags.Instance))
        {
            if (!ignoreList.Contains(pi.Name))
            {
                object selfValue = type.GetProperty(pi.Name).GetValue(self, null);
                object toValue = type.GetProperty(pi.Name).GetValue(to, null);

                if (selfValue != toValue && (selfValue == null ||   !selfValue.Equals(toValue)))
                {
                    return false;
                }
            }
        }
        return true;
    }
    return self == to;
}

但是最后一行self ==给出错误(Operator ==不能应用于class_name类型的操作数)

0 个答案:

没有答案