我有几个类都继承自同一个 Shape
类。当我创建一个新形状时,我希望它是随机形状。我想这样做的方法是创建一个列表,其中包含指向所有构造函数的链接,当我需要创建一个新形状时,我将从列表中随机获取一个构造函数并使用它来构造我的形状。我尝试以休闲方式创建列表,但出现错误:
List<Action> constList = new List<Action>();
constList.Add(SShape());
constList.Add(OShape());
constList.Add(LShape());
Shape
构造函数定义为:
class Shape
{
public Shape(PlayGrid grid, Color color)
{
...
}
...
}
每个子形状的构造函数定义如下:
class IShape : Shape
{
public IShape(PlayGrid grid, Color color) : base(grid, color)
{
...
}
...
}
构造列表的正确方法是什么,使用列表中的构造函数的方法是什么?
承包商还需要获取在不同形状之间变化的参数。
最佳答案
这个概念是可行的,你只是错误地使用了生成委托(delegate)的语法,而你想要一个 Func<PlayGrid, Color, Shape>
不是Action
:
var constList = new List<Func<PlayGrid, Color, Shape>>();
constList.Add((pg, c) => new SShape(pg, c));
PlayGrid playgrid = /* however you get this */;
Color color = /* however you get this */;
var shape = constList[randomIdx](playgrid, color);
关于c# - 是否可以在 c# 中创建一个构造函数列表来创建随机对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15570223/