简体   繁体   English

列表未排序

[英]List is not being ordered

I have this exercise and despite of my attempt to implement the IComparable interface I can't sort the list by weight from least to most............................................................................ 我进行了此练习,尽管尝试实现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());
            }
        }
    }
}

You've got the logic right, and it will sort correctly. 您的逻辑正确,它将正确排序。 However, your class definition is wrong: 但是,您的类定义是错误的:

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);
    }
}
  1. Both weight and name should be protected , not private, so that any subclass of Animal can read them. weightname都应受保护 ,而不是私有的,以便Animal任何子类都可以读取它们。
  2. name should be a string . name应该是string

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;
    }
}

Remove the fields weight and name from Cat . Cat删除字段weightname Currently, they're hiding the fields, so you're assigning values to Cat.weight , but sorting on Animal.weight . 当前,他们正在隐藏字段,因此您要为Cat.weight分配值,但要对Animal.weight排序。 Make these changes, and your code will work perfectly. 进行这些更改,您的代码将完美运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM