静态类成员到数组

时间:2014-04-08 11:25:17

标签: c#

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

我有什么:

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();

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

附加信息:静态类里面只包含静态字符串,因此一般的成员方法也是可行的,但我更喜欢该方法只返回给定类的静态字符串。

3 个答案:

答案 0 :(得分:3)

您可以通过 反射 执行此操作,语法略有不同

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

答案 1 :(得分:1)

public static class TypeExtension
{
    public static string[] GetStaticStrings(this Type type)
    {
        return type
                 .GetFields(BindingFlags.Public | BindingFlags.Static)
                 .Where(field => field.FieldType == typeof(string))
                 .Select(field => (string)field.GetValue(null))
                 .ToArray();
    }
}

用法:

string[] arr = typeof(A.BA).GetStaticStrings();

答案 2 :(得分:0)

我认为这将满足您的需求。基本上你需要一个类的实例来做A.BA,因为BA将是一个指向实例的字段的属性。

public static class A {
    public static readonly A_Wrapper BA = new A_Wrapper(
        new string[3] {
            "baa",
            "bab",
            "bac"
        }
    );

        public static readonly A_Wrapper BB = new A_Wrapper(
        new string[3] {
            "bba",
            "bbb",
            "bbc"
        }
    );

    public class A_Wrapper {
        public A_Wrapper(string[] data) {
            this.data = data;
        }
        private readonly string[] data;
        public string[] GetAllStringVariablesFromStaticMembers() {
            return data;
        }
    }
}

var data1 = A.BA.GetAllStringVariablesFromStaticMembers(); // baa, bab, bac
var data2 = A.BB.GetAllStringVariablesFromStaticMembers(); // bba, bbb, bbc