我有一个这样定义的结构
private struct Combinators
{
public const char DirectChild = '>';
public const char NextAdjacent = '+';
public const char NextSiblings = '~';
public const char Descendant = ' ';
}
我想使用反射来获取结构中 public const char
字段的所有值的列表(尽可能具体)。我该怎么做?
最佳答案
var fieldValues = typeof(Combinators)
.GetFields()
.Where(x => x.FieldType == typeof(char) && x.IsLiteral)
.ToDictionary(x => x.Name, x => (char)x.GetValue(null));
返回 Dictionary<string, char>
其中键是字段名称,值是字段值(作为字符)。
更新:根据评论和@nasufara 的建议添加了 where 子句,并添加了 IsLiteral
根据@Jeff M 的检查。
关于c# - 获得公共(public)领域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3898405/