C# 如何比较同一类的两个对象?

C# 如何比较同一类的两个对象?,c#,.net,oop,object,C#,.net,Oop,Object,我想知道如何比较两个对象(属于同一类),比如string.compare()方法 有什么方法可以做到这一点吗?您可以实现IComparable接口,如sugested: 您将使用CompareTo方法来比较类中的项目。有关IComparable的更多信息,请参见。使用CompareTo可以根据前面提到的比较功能对对象列表进行排序您需要实现IComparable接口 private class sortYearAscendingHelper : IComparer { int ICompa

我想知道如何比较两个对象(属于同一类),比如
string.compare()
方法


有什么方法可以做到这一点吗?

您可以实现
IComparable
接口,如sugested:


您将使用
CompareTo
方法来比较类中的项目。有关
IComparable
的更多信息,请参见。使用
CompareTo
可以根据前面提到的比较功能对对象列表进行排序

您需要实现IComparable接口

private class sortYearAscendingHelper : IComparer
{
   int IComparer.Compare(object a, object b)
   {
      car c1=(car)a;
      car c2=(car)b;
      if (c1.year > c2.year)
         return 1;
      if (c1.year < c2.year)
         return -1;
      else
         return 0;
   }
}
private class sortYearAscendingHelper:IComparer
{
int IComparer.Compare(对象a、对象b)
{
汽车c1=(汽车)a;
汽车c2=(汽车)b;
如果(c1年>c2年)
返回1;
如果(c1年

可以找到原始帖子

用于比较两个对象,请访问此处


因为对象是引用类型,所以应该使用obj.Equals()方法。 还请注意:

string.ReferenceEquals(str, str2);
它显然比较了参考文献

str.Equals(str2) 
首先尝试比较引用。然后,它尝试按值进行比较

str == str2

与Equals相同。

您可以检查两个相等引用相等和值相等

参考等式

引用相等意味着两个对象引用引用相同的基础对象。这可以通过简单的赋值实现,如下例所示

class Test
{
    public int Num { get; set; }
    public string Str { get; set; }

    static void Main()
    {
        Test a = new Test() { Num = 1, Str = "Hi" };
        Test b = new Test() { Num = 1, Str = "Hi" };

        bool areEqual = System.Object.ReferenceEquals(a, b);
        // Output will be false
        System.Console.WriteLine("ReferenceEquals(a, b) = {0}", areEqual);

        // Assign b to a.
        b = a;

        // Repeat calls with different results.
        areEqual = System.Object.ReferenceEquals(a, b);
        // Output will be true
        System.Console.WriteLine("ReferenceEquals(a, b) = {0}", areEqual);


    }
}
价值平等

值相等意味着两个对象包含相同的值。对于int或bool等基本值类型,值相等的测试非常简单

公共类基本实体
public class BaseEntity
{
    public int Id { get; set; }
}

public class Product : BaseEntity
{
   public string Name { get; set; }
   public decimal Price { get; set; }
}

//Generic Comparer
public class EntityComparer<T> :  IEqualityComparer<T>, IComparer<T> 
where T : BaseEntity
{
    public enum AscDesc : short
    {
        Asc, Desc
    }

    #region Const
    public string PropertyName { get; set; }
    public AscDesc SortType { get; set; }
    #endregion

    #region Ctor
    public EntityComparer(string _propertyname = "Id", AscDesc _sorttype = AscDesc.Asc)
    {
        this.PropertyName = _propertyname;
        this.SortType = _sorttype;
    }
    #endregion

    #region IComparer
    public int Compare(T x, T y)
    {
        if (typeof(T).GetProperty(PropertyName) == null)
            throw new ArgumentNullException(string.Format("{0} does not contain a property with the name \"{1}\"", typeof(T).Name, PropertyName));

        var xValue = (IComparable)x.GetType().GetProperty(this.PropertyName).GetValue(x, null);
        var yValue = (IComparable)y.GetType().GetProperty(this.PropertyName).GetValue(y, null);

        if (this.SortType == AscDesc.Asc)
            return xValue.CompareTo(yValue);

        return yValue.CompareTo(xValue);
    }
    #endregion

    #region IEqualityComparer
    public bool Equals(T x, T y)
    {
        if (typeof(T).GetProperty(PropertyName) == null)
            throw new InvalidOperationException(string.Format("{0} does not contain a property with the name -> \"{1}\"", typeof(T).Name, PropertyName));

        var valuex = x.GetType().GetProperty(PropertyName).GetValue(x, null);
        var valuey = y.GetType().GetProperty(PropertyName).GetValue(y, null);

        if (valuex == null) return valuey == null;

        return valuex.Equals(valuey);
    }

    public int GetHashCode(T obj)
    {
        var info = obj.GetType().GetProperty(PropertyName);
        object value = null;
        if (info != null)
        {
            value = info.GetValue(obj, null);
        }

        return value == null ? 0 : value.GetHashCode();
    }
    #endregion
}

 //Usage
 Product product = new Product();
 Product product2 =new Product();
 EntityComparer<Product> comparer = new EntityComparer<Product>("Propert Name Id Name whatever u want", Asc Or Desc);
 comparer.Compare(product, product2);
{ 公共int Id{get;set;} } 公共类产品:BaseEntity { 公共字符串名称{get;set;} 公共十进制价格{get;set;} } //通用比较器 公共类实体比较者:IEqualityComparer、IComparer 其中T:BaseEntity { 公共枚举AscDesc:短 { Asc,Desc } #区域常数 公共字符串PropertyName{get;set;} 公共AscDesc SortType{get;set;} #端区 #区域导体 public EntityComparer(string\u propertyname=“Id”,AscDesc\u sorttype=AscDesc.Asc) { this.PropertyName=\u PropertyName; this.SortType=\u SortType; } #端区 #区域IComparer 公共整数比较(TX,TY) { if(typeof(T).GetProperty(PropertyName)==null) 抛出新ArgumentNullException(string.Format(“{0}不包含名为\“{1}\”、类型为(T.name、PropertyName)的属性)); var xValue=(IComparable)x.GetType().GetProperty(this.PropertyName).GetValue(x,null); var yValue=(IComparable)y.GetType().GetProperty(this.PropertyName).GetValue(y,null); if(this.SortType==AscDesc.Asc) 返回xValue.CompareTo(yValue); 返回yValue.CompareTo(xValue); } #端区 #地区质量比较员 公共布尔等于(TX,TY) { if(typeof(T).GetProperty(PropertyName)==null) 抛出新的InvalidOperationException(string.Format(“{0}不包含名为->\“{1}\”、类型为(T.name、PropertyName)的属性); var valuex=x.GetType().GetProperty(PropertyName).GetValue(x,null); var valuey=y.GetType().GetProperty(PropertyName).GetValue(y,null); 如果(valuex==null)返回valuey==null; 返回值x等于(值y); } 公共int GetHashCode(T obj) { var info=obj.GetType().GetProperty(PropertyName); 对象值=空; 如果(信息!=null) { value=info.GetValue(obj,null); } 返回值==null?0:value.GetHashCode(); } #端区 } //用法 产品=新产品(); product2=新产品(); EntityComparer comparer=新的EntityComparer(“属性名称Id名称,无论您想要什么”,Asc或Desc); 比较(产品,产品2);
检查此链接重复项是错误的:该问题询问以相同的方式比较两个对象
string.Compare
,而重复项询问两个对象是否相等。这里投票最多的答案正好回答了所问的问题。
public class BaseEntity
{
    public int Id { get; set; }
}

public class Product : BaseEntity
{
   public string Name { get; set; }
   public decimal Price { get; set; }
}

//Generic Comparer
public class EntityComparer<T> :  IEqualityComparer<T>, IComparer<T> 
where T : BaseEntity
{
    public enum AscDesc : short
    {
        Asc, Desc
    }

    #region Const
    public string PropertyName { get; set; }
    public AscDesc SortType { get; set; }
    #endregion

    #region Ctor
    public EntityComparer(string _propertyname = "Id", AscDesc _sorttype = AscDesc.Asc)
    {
        this.PropertyName = _propertyname;
        this.SortType = _sorttype;
    }
    #endregion

    #region IComparer
    public int Compare(T x, T y)
    {
        if (typeof(T).GetProperty(PropertyName) == null)
            throw new ArgumentNullException(string.Format("{0} does not contain a property with the name \"{1}\"", typeof(T).Name, PropertyName));

        var xValue = (IComparable)x.GetType().GetProperty(this.PropertyName).GetValue(x, null);
        var yValue = (IComparable)y.GetType().GetProperty(this.PropertyName).GetValue(y, null);

        if (this.SortType == AscDesc.Asc)
            return xValue.CompareTo(yValue);

        return yValue.CompareTo(xValue);
    }
    #endregion

    #region IEqualityComparer
    public bool Equals(T x, T y)
    {
        if (typeof(T).GetProperty(PropertyName) == null)
            throw new InvalidOperationException(string.Format("{0} does not contain a property with the name -> \"{1}\"", typeof(T).Name, PropertyName));

        var valuex = x.GetType().GetProperty(PropertyName).GetValue(x, null);
        var valuey = y.GetType().GetProperty(PropertyName).GetValue(y, null);

        if (valuex == null) return valuey == null;

        return valuex.Equals(valuey);
    }

    public int GetHashCode(T obj)
    {
        var info = obj.GetType().GetProperty(PropertyName);
        object value = null;
        if (info != null)
        {
            value = info.GetValue(obj, null);
        }

        return value == null ? 0 : value.GetHashCode();
    }
    #endregion
}

 //Usage
 Product product = new Product();
 Product product2 =new Product();
 EntityComparer<Product> comparer = new EntityComparer<Product>("Propert Name Id Name whatever u want", Asc Or Desc);
 comparer.Compare(product, product2);