c# - 从静态类中选择一个随机静态变量

标签 c# .net static

我有一个静态类中的静态变量列表。

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/

相关文章:

c++ - C++ static 与 C 中的 static 相同吗?

c# - 在 Framework 4.6 项目中使用 .net core DLL

c# - C# 中的类型安全可区分联合,或 : How to limit the number of implementations of an interface?

c# - 如何从 C# 中的 QueryPerformanceCounter 获取刻度?

c# - 从 C++ 调用 C# dll 时如何使用 app.config 文件

c# - Azure表存储: maximum variable size?

C# - 在 Windows 窗体应用程序中获取 SelectedItem 的值

c# - 如何获取网址的内容类型?

java - 在 Java 中,在一个子类中将变量设置为 Final 和 static,同时在其他子类中保持变量不变

java - 从对象和类本身调用静态函数之间的区别