日期:2014-05-17  浏览次数:20957 次

用类计算矩形的面积,并且比较两个矩形面积的大小
设计一个矩形类,要求能够计算矩形的面积,比较两个矩形面积的大小

------解决方案--------------------


sealed class Rectangle :IComparable
    {
        public double Length { get; set; }

        public double Width { get; set; }

        public Rectangle()
        { }

        public Rectangle(double length, double width)
        {
            this.Length = length;
            this.Width = width;
        }

        public double GetArea()
        {
            return this.Length * this.Width;
        }

        int IComparable.CompareTo(object obj)
        {
            if (obj is Rectangle)
                return this.GetArea().CompareTo(((Rectangle)obj).GetArea());

            throw new ArgumentException("参数obj不是Rectangle的实例");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            IComparable r1 = new Rectangle(2, 2);
            IComparable r2 = "hello world";

            Console.WriteLine(r1.CompareTo(r2));

        }
    }


------解决方案--------------------
曹版看见了,又会给你锁了,LZ怎么天天要作业题呢?
GetArea计算面积。
CompareTo 比较大小。
------解决方案--------------------
不是调试不出来,我只是测试一下那个异常能否正确的抛出来
修改成这样


IComparable r1 = new Rectangle(2, 2);
IComparable r2 = new Rectangle(3, 3);
Console.WriteLine(r1.CompareTo(r2));