使用变量作为类型并实例化它

Jes*_*per 6 c#

首先,我想说我是C#的新手,所以这个问题似乎完全偏离了轨道.

我有一组名为ShapeType的枚举:

Cube, Sphere, Rectangle, Ellipse
Run Code Online (Sandbox Code Playgroud)

以及从枚举中返回随机值的方法:

private static ShapeType GetRandomShape()
{
    Array values = Enum.GetValues(typeof(ShapeType));
    Random random = new Random();
    ShapeType randomShape = (ShapeType)values.GetValue(random.Next(values.Length));
    return randomShape;
}
Run Code Online (Sandbox Code Playgroud)

每个可枚举的都有相应的具体类.我想知道的问题是,如果你可以使用随机可枚举值randomShape来实例化一个类,有点像这样:

private static Shape GetRandomShape()
{
    Array values = Enum.GetValues(typeof(ShapeType));
    Random random = new Random();
    ShapeType randomShape = (ShapeType)values.GetValue(random.Next(values.Length));
    Shape shape = new randomShape(); // *Here use the randomShape-variable as type*
    return shape;
}
Run Code Online (Sandbox Code Playgroud)

这可能还是只是一厢情愿的想法?

Ale*_*ria 3

您可以使用字典来检索枚举的每个值的工厂函数:

static readonly Dictionary<ShapeType, Func<Shape>> _factoryLookup = new Dictionary<ShapeType, Func<Shape>>
{
    [ShapeType.Cube] = () => new Cube(),
    [ShapeType.Ellipse] = () => new Ellipse(),
    [ShapeType.Rectangle] = () => new Rectangle(),
    [ShapeType.Sphere] = () => new Sphere(),
};

static readonly Random random = new Random();

private static Shape GetRandomShape()
{
    Array values = Enum.GetValues(typeof(ShapeType));
    ShapeType randomShape = (ShapeType)values.GetValue(random.Next(values.Length));
    Func<Shape> factory = _factoryLookup[randomShape];
    Shape shape = factory();
    return shape;
}
Run Code Online (Sandbox Code Playgroud)