【问题标题】:Loop through public constants in a static class [duplicate]循环遍历静态类中的公共常量[重复]
【发布时间】:2019-07-28 00:31:30
【问题描述】:

这篇SO 帖子讨论了属性,但是我试图获取以下静态类中的常量:

public static class SpYtMessageConstants
{
    public const int MSG_NOOP = 1;
    public const int MSG_PING = 2;
}

我想遍历所有常量并获取每个值的值。这是用于单元测试以确保没有人两次添加相同的值。

【问题讨论】:

  • @HimBromBeere 如果您查看我的原始帖子,您会看到我引用了完全相同的帖子。然而,它正在处理访问常量的属性,而不是像我的情况那样直接访问常量。所以这不是一个直接的答案。
  • 如果您也只阅读了其他答案,而不仅仅是已接受的答案,那么您自己就会得到解决方案。无论如何,这里有另一个副本:stackoverflow.com/questions/10261824/…

标签: c# reflection


【解决方案1】:

我们希望static(和publicfields'(不是属性)值只能在编译时设置(IsLiteral)而不是readonly - @987654325 @

Object[] values = typeof(SpYtMessageConstants)
  .GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy)
  .Where(f => f.IsLiteral && !f.IsInitOnly)
  .Select(f => f.GetValue(null))
  .ToArray();

最后,在您的特定情况下,BindingFlags.FlattenHierarchy 是多余的,但是,如果类被继承,它会很有用:

public class BaseClass {
  public const int BaseConst = 123;
}

public class DerivedClass : BaseClass {
  public const int DerivedConst = 456;
}

如果BindingFlags.FlattenHierarchy 指定 BaseConstDerivedConst 都返回

【讨论】:

    猜你喜欢
    • 2016-10-25
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 2018-10-15
    • 2018-05-20
    • 1970-01-01
    相关资源
    最近更新 更多