列表未被订购

时间:2016-03-02 03:27:20

标签: c# list sorting

我有这个练习,尽管我尝试实现IComparable接口,但我无法按重量从最少到最多排序列表.................... .................................................. ......

using System;
using System.Collections.Generic;
namespace Program
{
    abstract class Animal : IComparable<Animal>
    {
        private double weight;
        private int name;
        abstract public override string ToString();
        public int CompareTo(Animal right)
        {
            return weight.CompareTo(right.weight);
        }
    }
    class Cat : Animal
    {
        public Cat(double weight, string name)
        {
            this.weight = weight;
            this.name = name;
        }
        private double weight;
        private string name;
        public override string ToString()
        {
            return "I'm the cat " + name + " and I weight " + weight;
        }
    }
    class Hello
    {
        static void Main(string[] args)
        {
            List<Animal> myArray = new List<Animal>();
            for (int counter = 9; counter > 0; counter--)
            {
                myArray.Add(new Cat(counter * 3.5, counter.ToString()));
            }
            foreach (Animal CatOrDog in myArray)
            {
                Console.WriteLine(CatOrDog.ToString());
            }
            myArray.Sort();
            foreach (Animal CatOrDog in myArray)
            {
                Console.WriteLine(CatOrDog.ToString());
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

你的逻辑是正确的,它会正确排序。但是,您的类定义是错误的:

name
  1. Animalname都应该受保护,而不是私有,因此string的任何子类都可以读取它们。
  2. class Cat : Animal { public Cat(double weight, string name) { this.weight = weight; this.name = name; } private double weight; private string name; public override string ToString() { return "I'm the cat " + name + " and I weight " + weight; } } 应为weight
  3. name

    Cat中删除字段Cat.weightAnimal.weight。目前,他们正在隐藏字段,因此您需要将值分配给'str' object has not attribute 'subs',但要对from sympy import * x,a_test,b_test,fa_test,fb_test=symbols('x a_test b_test fa_test fb_test') expr=raw_input("enter the equation") print expr print "hello" try: print "hello" inc=0 a=inc fa=expr.subs(x,inc) print "hello" if(fa<0): print "hello" inc+=1 fb=expr.subs(x,inc) if(fb<=0): while(fb<=0): inc+=1 else: print "hello" inc+=1 fb=expr.subs(x,inc) if(fb<=0): while(fb<=0): inc+=1 b=inc print a print b print fa print fb except Exception,e: print e 进行排序。进行这些更改,您的代码将完美运行。