2013-12-24 4 views
3

Я хочу знать, как я могу сравнить два объекта (которые имеют тот же класс), что и метод string.Compare().Как сравнить два объекта одного класса?

Есть ли способ сделать это?

+0

проверить эту ссылку http://stackoverflow.com/questions/5183929/comparing-two-objects –

+0

http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80) .aspx –

ответ

7

Вы можете реализовать IComparable интерфейс, как мотивационные here:

public class Temperature : IComparable 
{ 
    // The temperature value 
    protected double temperatureF; 

    public int CompareTo(object obj) { 
     if (obj == null) return 1; 

     Temperature otherTemperature = obj as Temperature; 
     if (otherTemperature != null) 
      return this.temperatureF.CompareTo(otherTemperature.temperatureF); 
     else 
      throw new ArgumentException("Object is not a Temperature"); 
    } 
    ... 

source

Вы будете иметь CompareTo метод, который будет сравнить элементы вашего класса. Подробнее о IComparable можно найти здесь: SO. Имея CompareTo, вы можете сортировать списки по объектам в соответствии с функцией сравнения, например, указанным here

1

Вам необходимо реализовать интерфейс 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; 
    } 
} 

Оригинальный пост можно найтиHere

1

поскольку объекты являются ссылочными типами, поэтому вы должны использовать obj.Equals() способ. также отметить, что:

string.ReferenceEquals(str, str2); 

Это, очевидно, сравнивает ссылки.

str.Equals(str2) 

Сначала пытается сравнить ссылки. Затем он пытается сравнить по значению.

str == str2 

Имеет то же значение, что и равное.

1

Вы можете проверить два равенства Ссылка равенства и значение равенства

Ссылка равенство

Reference равенство означает, что две объектные ссылки ссылаются на тот же базовый объект. Это может произойти посредством простого назначения, как показано в следующем примере.

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, тесты для равенства значений являются простыми.

0
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); 
Смежные вопросы