【问题标题】:System.Reflection GetNestetTypes All fields declared Name or valueSystem.Reflection GetNestetTypes 声明的所有字段名称或值
【发布时间】:2013-06-08 22:07:59
【问题描述】:

如何获取所有嵌套类中所有字段的列表

class AirCraft
{
    class fighterJets
    {
        public string forSeas = "fj_f18";
        public string ForLand = "fj_f15";
    }
    class helicopters 
    {
        public string openFields = "Apachi";
        public string CloseCombat = "Cobra";

    }
}

我尝试使用的代码来自这里的一篇帖子 我可以把它分成两到三行单独的代码,它会起作用 问题是关于表达式,以及使用最短/现代代码。

IEnumerable<FieldInfo> GetAllFields(Type type) {
    return type.GetNestedTypes().SelectMany(GetAllFields)
               .Concat(type.GetFields());
}

这将返回 fieldInfo 而不是名称或值, 我更需要它作为字符串列表或更适合字段值和名称的字典 但现在可以列出一个列表。

List<string> (or dictionary) ChosenContainersNamesOrValuesOfAllNested(Type T)
{
   return a shortest syntax for that task, using lambda rather foreach
}

谢谢。

【问题讨论】:

  • 如果没有每个类的实例,您如何获取字段的值?您的字段不是静态的。
  • @KirkWoll 在我的程序中。虽然很高兴看到有和没有实例的例子
  • 如果在您的“程序中”,那么它在您发布的代码之外的其他地方。

标签: c# reflection nested-class fieldinfo


【解决方案1】:

您可以只使用 Linq 的 Select 扩展方法来获取名称:

IEnumerable<string> GetAllFieldNames(Type type)
{
    // uses your existing method
    return GetAllFields(type).Select(f => f.Name);
}

或者ToDictionary扩展方法构造字典:

IDictionary<string, object> GetAllFieldNamesAndValues(object instance) 
{
    return instance.GetType()
        .GetFields()
        .ToDictionary(f => f.Name, f => f.GetValue(instance));
}

请注意,您将需要该类型的实例来获取值。此外,这仅适用于单一类型,因为您需要每种类型的实例来获取值。

但是,如果您将字段定义为静态,您可以这样做:

class AirCraft
{
    public class fighterJets
    {
        public static string forSeas = "fj_f18";
        public static string ForLand = "fj_f15";
    }
    public class helicopters 
    {
        public static string openFields = "Apachi";
        public static string CloseCombat = "Cobra";

    }
}

IEnumerable<FieldInfo> GetAllStaticFields(Type type) 
{
    return type.GetNestedTypes().SelectMany(GetAllFields)
               .Concat(type.GetFields(BindingFlags.Public | BindingFlags.Static));
}


IDictionary<string, object> GetAllStaticFieldNamesAndValues(Type type) 
{
    return GetAllStaticFields(type)
        .ToDictionary(f => f.Name, f => f.GetValue(null));
}

这是可行的,因为静态字段没有绑定到类的任何实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-23
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    相关资源
    最近更新 更多