【发布时间】:2020-10-23 14:35:06
【问题描述】:
我想从嵌套类中的所有常量创建一个列表。
public struct SomePair
{
public string Name, Value;
public SomePair(string name, string value)
{
Name = name;
Value = value;
}
}
private static MemberInfo[] GetClasses() => typeof(MainFoo).GetMembers(BindingFlags.Public);
private static List<Type> GetClassTypes() => GetClasses().Select(c=>c.GetType()).ToList();
public static class MainFoo
{
// The return value should contain the information about the SomeConstant's from both Errors and Foo.
public static List<LocalizationPair> Dump()
{
List<SomePair> Dump = new List<SomePair>();
var classes = GetClassTypes();
foreach (Type cls in classes)
{
var constants = cls.GetFields(BindingFlags.Public); // <<< Is always empty...
foreach (FieldInfo constant in constants)
{
Dump.Add(new SomePair(
$"{cls.Name}.{constant.Name}",
constant.GetValue(cls).ToString()
));
}
}
return Dump;
}
public static class Errors
{
public constant string SomeConstant = "a";
}
public static class Foo
{
public constant string SomeConstant = "a";
}
}
我能够获得所有类的列表和所有类类型的列表,但是一旦我尝试对它们使用 GetMember(),它什么也不会返回。
【问题讨论】:
-
我在任何地方都没有看到对
GetNestedTypes的呼叫,所以从那里开始。其次,您需要包含BindingFlags.Instance和/或BindingFlags.Static以获得任何结果。常量是静态成员。第三,.Select(c => c.GetType())将从序列中为RuntimeFieldInfo、RuntimePropertyInfo等投影Type实例。您需要将每个项目 (c) 转换为FieldInfo、PropertyInfo等,具体取决于它是什么,并分别获取FieldType或PropertyType属性。它不会是一个简单的 lambda 表达式。 -
谢谢,解决了。我什至不知道这种方法存在。
标签: c# reflection constants