【发布时间】:2017-05-04 20:50:19
【问题描述】:
首先,我想说我是 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;
}
这是可能的还是只是一厢情愿?
【问题讨论】:
-
“每个可枚举都有一个对应的具体类” - 您可以使用字典将枚举值映射到相应的类型/实例。另一种选择是根本不使用枚举,而是隐含到
int转换(现在使用枚举值)。
标签: c#