gpt4 book ai didi

c# - 列表需要类型参数

转载 作者:行者123 更新时间:2023-12-03 22:59:45 25 4
gpt4 key购买 nike

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

多态示例程序如下。

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<T> class 的文档,你会注意到 Listgeneric类型(因此是 <T> ),泛型类型需要一个(或更多)参数来指定它将使用/包含的对象的类型。您必须指定某些类型,即使它只是 object

就您而言,您有一个列表 Shape对象,因此可以修改您的初始化代码(并通过使用集合初始值设定项语法进行简化)以指定该类型:

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

关于c# - 列表需要类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53838866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com