undefinedfix
Sign in

An error in C # interface

Lancet edited in Fri, 30 Sep 2022
namespace ConsoleApp11
{
    interface IComparable
    {
        int CompareTo(object ob);
    }

    class Myclass: IComparable
    {
        int theElement;
        public int _TheElement
        {
            set
            {
                theElement = value;
            }
            get
            {
                return theElement;
            }
        }
        public int CompareTo(object ob)
        {
            Myclass m = (Myclass)ob;
            if (theElement > m.theElement)
                return 1;
            else if (theElement < m.theElement)
                return -1;
            return 0;
        }
    }
    class program
    {
        static void print(Myclass[] my)
        {
            foreach (var m in my)
                Console.Write("{0} ", m._TheElement);
            Console.WriteLine("");
        }
        static void Main()
        {
            Myclass[] M = new Myclass[4];
            for (int i = 0; i < M.Length; ++i)
                M[i] = new Myclass() { _TheElement = M.Length-i };

            print(M);
            Array.Sort(M);
            print(M);
            Console.ReadLine();
        }
    }
}

图片描述

The interface has been implemented, but the error can not be compared

1 Replies
Braden
commented on Fri, 30 Sep 2022

The interface it needs to implement is not IComparable, but System.IComparabale