【问题标题】:Is there a function that returns the class const names [duplicate]是否有返回类常量名称的函数[重复]
【发布时间】:2014-10-12 03:15:27
【问题描述】:

有没有办法将 const 名称读入列表?

示例代码

public static class Cars
{
    public const int Length= 10;
    public const int Height= 15;
    public const int Weight = 20;
}

【问题讨论】:

  • Cars 中没有方法,只有字段
  • 更重要的是,为什么你想这样做?您可能试图从错误的角度解决问题。
  • 我已经编辑了这个问题。我只有这些类可以从中获取信息,并且需要获取此 const 名称和值的列表,以显示在屏幕上!

标签: c#


【解决方案1】:

你可以像这样使用反射。

var fields = typeof(Cars)
    .GetFields(BindingFlags.Public | BindingFlags.Static)
    .Select(f => new { Name = f.Name, Value = f.GetValue(null) })
    .ToList();

【讨论】:

  • 看起来你打字快了几秒钟;-)
  • 哇,答案几乎是一样的,而且你同时写了:)你们俩都做得很好!
【解决方案2】:

是的:

typeof(Cars).GetFields(BindingFlags.Instance |BindingFlags.Static | BindingFlags.Public).Select(m => m.Name)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2019-05-04
    相关资源
    最近更新 更多