我有一个静态类中的静态变量列表。
namespace Test
{
public static class Numbers
{
public static readonly int One = 1;
public static readonly int Five = 5;
public static readonly int Ten = 10;
public static readonly int Eleven = 11;
public static readonly int Fifteen= 15;
}
}
我想在类(class)中随机选择一个变量。我怎样才能做到这一点?
int randomVariable = SomeFunction(Numbers);
最佳答案
使用反射:
FieldInfo[] fields= typeof(Numbers).GetFields(
BindingFlags.Public | BindingFlags.Static);
var rnd = new Random();
int randomVariable = (int) fields[rnd.Next(fields.Length)].GetValue(null);
没有反射的更好解决方案:
创建一个整数数组 Numbers
作为静态属性并将其初始化为类 Numbers
中的值:
Numbers = fields.Select(f => (int)f.GetValue()).ToArray(); //int[]
然后在获取随机值时:
int randomVariable = Numbers[rnd.Next(Numbers.Length)];
关于c# - 从静态类中选择一个随机静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16934529/