【问题标题】:List requires a type argument列表需要类型参数
【发布时间】:2019-05-19 05:10:24
【问题描述】:

编译代码时出现三个错误。 1.使用泛型 List 需要 1 个参数。 2.使用泛型 List 需要 1 个参数。 3. foreach 语句不能对类型变量进行操作,因为 List 不包含 'GetEnumerator' 的公共定义

多态示例的程序如下。

namespace PolymorExample
{
    abstract class Shape
    {
        public abstract void area();
    }

    class Rectangle : Shape
    {
        private double length;
        private double width;

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

        public override void area()
        {
            Console.WriteLine("Rectangel Area: {0}", length * width);
        }
    }

    class Triangle : Shape
    {
        private double baseline;
        private double height;

        public Triangle(double baseline, double height)
        {
            this.baseline = baseline;
            this.height = height;
        }

        public override void area()
        {
            Console.WriteLine("Triangel Area: {0}", baseline * height / 2.0);
        }
    }

    class Circle : Shape
    {
        const double PI = 3.14;
        private double radius;

        public Circle(double radius)
        {
            this.radius = radius;
        }

        public override void area()
        {
            Console.WriteLine("Circle Area: {0}", radius * radius * PI);
        }
    }

    public class TestShape
    {
        static void Main()
        {
            List shapes = new List();
            Shape shape1 = new Rectangle(10, 10);
            shapes.Add(shape1);
            shapes.Add(new Circle(10));
            shapes.Add(new Triangle(10, 10));
            shapes.Add(new Circle(20));

            foreach (Shape s in shapes)
            {
                s.area();
            }

            Console.Read();
        }
    }
}

【问题讨论】:

  • 试试List<Shape>
  • 据我所知,.NET Framework 中没有 non-generic List 类型。您必须指定类型参数:List<Shape>

标签: c# list oop object-oriented-analysis


【解决方案1】:
List<Shape> shapes = new List<Shape>();

您需要列表声明中的形状类型,以便它知道它的列表

【讨论】:

    【解决方案2】:

    如果您查看List&lt;T&gt; class 的文档,您会注意到Listgeneric 类型(因此是&lt;T&gt;),而泛型类型需要一个(或更多)参数指定它将使用/包含的对象的类型。您必须指定 some 类型,即使它只是 object

    在您的情况下,您有一个 Shape 对象列表,因此可以修改您的初始化代码(并通过使用集合初始化器语法简化)以指定该类型:

    var shapes = new List<Shape>
    {
        new Rectangle(10, 10),
        new Circle(10),
        new Triangle(10, 10),
        new Circle(20)
    };
    

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多