C# 比较2个对象的通用代码
我有两个不同的对象,需要比较它们是否相等 我可以使用反射编写一些代码来比较属性值,但我想知道在.NET4.0中是否有任何新模式可以解决这个问题 我可以使用反射编写一些代码来比较属性值,但我想知道在.NET4.0中是否有任何新模式可以解决这个问题 不,你得自己写 我可以使用反射编写一些代码来比较属性值,但我想知道在.NET4.0中是否有任何新模式可以解决这个问题C# 比较2个对象的通用代码,c#,.net,comparison,data-annotations,C#,.net,Comparison,Data Annotations,我有两个不同的对象,需要比较它们是否相等 我可以使用反射编写一些代码来比较属性值,但我想知道在.NET4.0中是否有任何新模式可以解决这个问题 我可以使用反射编写一些代码来比较属性值,但我想知道在.NET4.0中是否有任何新模式可以解决这个问题 不,你得自己写 我可以使用反射编写一些代码来比较属性值,但我想知道在.NET4.0中是否有任何新模式可以解决这个问题 不可以。您必须自己编写。您可以在公共接口中实现公共比较属性,并将其作为该接口类型进行比较。您可以在公共接口中实现公共比较属性,并将其作为
不可以。您必须自己编写。您可以在公共接口中实现公共比较属性,并将其作为该接口类型进行比较。您可以在公共接口中实现公共比较属性,并将其作为该接口类型进行比较。您需要类来实现
IComparable
然后重写并实现CompareTo
方法,以帮助C#了解如何比较这些对象
作为一个例子,我想比较两个小部件。它是一个包含整数和字符串的复杂类。我相信整数和字符串长度的组合将决定哪个对象更大
Class MyWidget : IComparable
{
public int Piece { get; set; }
public string Thing { get; set; }
public MyWidget()
{
this.Piece = 1;
this.Thing = "default";
}
public int CompareTo(object obj)
{
var otherWidget = obj as MyWidget;
if (otherWidget != null)
{
return (this.Piece + this.Thing.Length).CompareTo(otherWidget.Piece + otherWidget.Thing.Length);
}
else
{
throw new ArgumentException("Object is not a MyWidget");
}
}
}
您需要您的类实现
IComparable
,然后重写并实现CompareTo
方法,以帮助C#理解它应该如何比较这些对象
作为一个例子,我想比较两个小部件。它是一个包含整数和字符串的复杂类。我相信整数和字符串长度的组合将决定哪个对象更大
Class MyWidget : IComparable
{
public int Piece { get; set; }
public string Thing { get; set; }
public MyWidget()
{
this.Piece = 1;
this.Thing = "default";
}
public int CompareTo(object obj)
{
var otherWidget = obj as MyWidget;
if (otherWidget != null)
{
return (this.Piece + this.Thing.Length).CompareTo(otherWidget.Piece + otherWidget.Thing.Length);
}
else
{
throw new ArgumentException("Object is not a MyWidget");
}
}
}
如果要比较对象,可能需要重新定义Equals()函数,如下所示:
public override bool Equals(Object obj)
{
User testedUser = (User)obj;
if (this._userName == testedUser.UserName &&
this._userPassword == testedUser.UserPassword)
{
return true;
}
else
{
return false;
}
}
然后,您只需执行一个:userbob.Equals(userAnne)如果要比较对象,您可能需要重新定义Equals()函数,如下所示:
public override bool Equals(Object obj)
{
User testedUser = (User)obj;
if (this._userName == testedUser.UserName &&
this._userPassword == testedUser.UserPassword)
{
return true;
}
else
{
return false;
}
}
然后,您可以简单地执行:userbob.Equals(userAnne)对于比较大型obejct图的快速而肮脏的方法,将每边转储到,然后使用一个 对于比较大型obejct图的快速而肮脏的方法,请将每一侧转储到,然后使用一个 问题是什么是平等?超越==框架不知道您想要什么样的平等。问题是什么是平等?超越==框架不知道您想要什么类型的相等。不是很简单-如果重写等于,您还应该重写GetHashCode-。用于确定相等性的属性实际上应该是不可变的。不太简单-如果重写等于,还应该重写GetHashCode-。用于确定相等性的属性实际上应该是不可变的。