gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:32:25 24 4
gpt4 key购买 nike

首先,我想说我是 C# 的新手,所以这个问题可能看起来完全偏离了正轨。

我有一组名为 ShapeType 的枚举:

Cube, Sphere, Rectangle, Ellipse

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

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

每个可枚举都有一个相应的具体类。我想知道的问题是,您是否可以使用随机可枚举值 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;
}

这是可能的还是一厢情愿?

最佳答案

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

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

关于c# - 使用变量作为类型并实例化它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43782962/

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