我如何获得一个数组,其中包含类的所有静态字符串?

是)我有的:

public static class A
{
    public static class BA
    {
        public const string BAA = "baa";
        public const string BAB = "bab";
        public const string BAC = "bac";
    }
    public static class BB
    {
        public const string BBA = "bba";
        public const string BBB = "bbb";
        public const string BBC = "bbc";
    }
}


我想要的是:

string[] BAs = new string[]{"baa","bab","bac"};
string[] BBs = new string[]{"bba","bbb","bbc"};


也会很好(但更喜欢上面的解决方案):

string[] BAs = new string[]{"BAA","BAB","BAC"};
string[] BBs = new string[]{"BBA","BBB","BBC"};


一些伪代码:

string[] BAs = A.BA.GetAllStringVariablesFromStaticMembers();
string[] BBs = A.BB.GetAllStringVariablesFromStaticMembers();


这有可能吗?如果是的话,我该怎么办?

附加信息:静态类仅在其中包含静态字符串,因此也可以使用常规成员方法,但是如果该方法仅返回给定类的静态字符串,则我更喜欢。

最佳答案

您可以通过反射使用稍微不同的语法来做到这一点:

public static String[] GetAllStringVariablesFromStaticMembers(Type value) {
  if (Object.ReferenceEquals(null, value))
    throw new ArgumentNullException("value");

  List<String> result = new List<String>();

  foreach (FieldInfo fi in value.GetFields(BindingFlags.Static | BindingFlags.Public))
    if (fi.FieldType == typeof(String))
      result.Add(fi.GetValue(null) as String);

  return result.ToArray();
}

...

string[] BAs = GetAllStringVariablesFromStaticMembers(typeof(A.BA));

关于c# - 静态类成员到数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22935536/

10-17 02:03