如何通过一个公共属性将两个自定义对象相互比较?

我有一个具有以下属性的电影对象

public class Movie {
    private string title;
    ...other similar properties...
}

如何实现在二叉树中使用的CompareTo()类?

我到目前为止所做的是

public int CompareTo(object obj)
{
    Movie m1 = (Movie)obj;

    return this.title.CompareTo(m1.title);
}

By trying to use the pre-existing CompareTo() function in string, but it won't work.
评论
  • verror
    verror 回复

    这就是实现CompareTo的方式

           static void Main(string[] args)
            {
                var m1 = new Movie() { title = "a1" };
                var m2 = new Movie() { title = "a0" };
                if (m1.CompareTo( m2) == 0)
                {
                    Console.WriteLine("equal");
                }
                else
                {
                    Console.WriteLine("not equal");
                }
    
            }        
    
           public class Movie: IComparable
            {
                public string title;
    
                public int CompareTo(object obj)
                {
                    Movie m1 = (Movie)obj;
                    return this.title.CompareTo(m1.title);
                }
            }