【问题标题】:How to get the list of properties of a class?如何获取类的属性列表?
【发布时间】:2010-10-18 17:44:38
【问题描述】:

如何获得一个类的所有属性的列表?

【问题讨论】:

  • This 可能也有帮助。

标签: c# .net reflection properties


【解决方案1】:

以下代码将为您提供类属性/属性/表列的列表

var Properties = typeof(className).GetProperties().Select(x=>x.Name).Tolist();

【讨论】:

    【解决方案2】:

    试试这个:

    var model = new MyObject();
    foreach (var property in model.GetType().GetProperties())
    {
        var descricao = property;
        var type = property.PropertyType.Name;
    }
    

    【讨论】:

    • 这回答了OP以最直接的方式提出的问题。 6行就完成了。
    【解决方案3】:

    您可以使用 Reflection 来做到这一点: (来自我的库 - 这会获取名称和值)

    public static Dictionary<string, object> DictionaryFromType(object atype)
    {
        if (atype == null) return new Dictionary<string, object>();
        Type t = atype.GetType();
        PropertyInfo[] props = t.GetProperties();
        Dictionary<string, object> dict = new Dictionary<string, object>();
        foreach (PropertyInfo prp in props)
        {
            object value = prp.GetValue(atype, new object[]{});
            dict.Add(prp.Name, value);
        }
        return dict;
    }
    

    这对带有索引的属性不起作用——因为它(它变得笨拙):

    public static Dictionary<string, object> DictionaryFromType(object atype, 
         Dictionary<string, object[]> indexers)
    {
        /* replace GetValue() call above with: */
        object value = prp.GetValue(atype, ((indexers.ContainsKey(prp.Name)?indexers[prp.Name]:new string[]{});
    }
    

    另外,只获取公共属性:(see MSDN on BindingFlags enum)

    /* replace */
    PropertyInfo[] props = t.GetProperties();
    /* with */
    PropertyInfo[] props = t.GetProperties(BindingFlags.Public)
    

    这也适用于匿名类型!
    仅获取名称:

    public static string[] PropertiesFromType(object atype)
    {
        if (atype == null) return new string[] {};
        Type t = atype.GetType();
        PropertyInfo[] props = t.GetProperties();
        List<string> propNames = new List<string>();
        foreach (PropertyInfo prp in props)
        {
            propNames.Add(prp.Name);
        }
        return propNames.ToArray();
    }
    

    对于值来说几乎相同,或者您可以使用:

    GetDictionaryFromType().Keys
    // or
    GetDictionaryFromType().Values
    

    但我想这有点慢。

    【讨论】:

    • ...但是atype.GetProperty(prp.Name) 会返回prp?
    • 关于公共属性位,根据链接的 MSDN 文章:“注意您必须指定 Instance 或 Static 以及 Public 或 NonPublic,否则不会返回任何成员。”。所以示例代码应该是:t.GetProperties(BindingFlags.Instance | BindingFlags.Public)t.GetProperties(BindingFlags.Static | BindingFlags.Public)
    • 不是在寻找代码,而是在寻找反射的解释,哇,非常感谢!把它变成通用的,你还不如说你的程序有超能力;)
    【解决方案4】:

    根据@MarcGravell 的回答,这里有一个适用于 Unity C# 的版本。

    ObjectsClass foo = this;
    foreach(var prop in foo.GetType().GetProperties()) {
        Debug.Log("{0}={1}, " + prop.Name + ", " + prop.GetValue(foo, null));
    }
    

    【讨论】:

      【解决方案5】:

      这是改进的@lucasjones 答案。在他回答之后,我在评论部分提到了改进。我希望有人会觉得这很有用。

      public static string[] GetTypePropertyNames(object classObject,  BindingFlags bindingFlags)
      {
          if (classObject == null)
          {
              throw new ArgumentNullException(nameof(classObject));
          }
      
              var type = classObject.GetType();
              var propertyInfos = type.GetProperties(bindingFlags);
      
              return propertyInfos.Select(propertyInfo => propertyInfo.Name).ToArray();
       }
      

      【讨论】:

      • 我想你可以编辑他的答案,而不是自己做。基本上,看哪个给出相同的观点会少一个答案。
      【解决方案6】:

      这就是我的解决方案

      public class MyObject
      {
          public string value1 { get; set; }
          public string value2 { get; set; }
      
          public PropertyInfo[] GetProperties()
          {
              try
              {
                  return this.GetType().GetProperties();
              }
              catch (Exception ex)
              {
      
                  throw ex;
              }
          }
      
          public PropertyInfo GetByParameterName(string ParameterName)
          {
              try
              {
                  return this.GetType().GetProperties().FirstOrDefault(x => x.Name == ParameterName);
              }
              catch (Exception ex)
              {
      
                  throw ex;
              }
          }
      
          public static MyObject SetValue(MyObject obj, string parameterName,object parameterValue)
          {
              try
              {
                  obj.GetType().GetProperties().FirstOrDefault(x => x.Name == parameterName).SetValue(obj, parameterValue);
                  return obj;
              }
              catch (Exception ex)
              {
                  throw ex;
              }
          }
      }
      

      【讨论】:

      • 请。请永远不要这样做。这个 S.O.应该尽最大努力回答关于应该做某事的方式的问题。如果您的库要求甚至允许使用成员名称的字符串表示来更改您的强类型对象,那么您的代码库就存在很大问题。并不是说这在某些情况下没有必要,因为您可能显然无法控制系统的其他部分、公司政治或其他事情。但这看起来像是一个架构决策,而且是一个可怕的决策。这是一系列可怕的编程选择中的一个决定。
      【解决方案7】:
      public List<string> GetPropertiesNameOfClass(object pObject)
      {
          List<string> propertyList = new List<string>();
          if (pObject != null)
          {
              foreach (var prop in pObject.GetType().GetProperties())
              {
                  propertyList.Add(prop.Name);
              }
          }
          return propertyList;
      }
      

      此函数用于获取类属性列表。

      【讨论】:

      • 您可能希望将其更改为使用yield return。这没什么大不了的,但这是一种更好的方法。
      • 我喜欢这个,因为它(几乎)是唯一不包含 reflection 这个词的答案。
      • 但这仍然使用反射。
      • 我想这更好 pObject.GetType().GetProperties().Select(p=>p.Name)
      【解决方案8】:

      我也面临这种需求。

      从这次讨论中我得到了另一个想法,

      Obj.GetType().GetProperties()[0].Name
      

      这也显示了属性名称。

      Obj.GetType().GetProperties().Count();
      

      这显示了属性的数量。

      谢谢大家。这是很好的讨论。

      【讨论】:

        【解决方案9】:

        反射;例如:

        obj.GetType().GetProperties();
        

        对于一个类型:

        typeof(Foo).GetProperties();
        

        例如:

        class Foo {
            public int A {get;set;}
            public string B {get;set;}
        }
        ...
        Foo foo = new Foo {A = 1, B = "abc"};
        foreach(var prop in foo.GetType().GetProperties()) {
            Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
        }
        

        以下反馈...

        • 要获取静态属性的值,请将null 作为第一个参数传递给GetValue
        • 要查看非公共属性,请使用(例如)GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)(它返回所有公共/私有实例属性)。

        【讨论】:

        • 为了完整起见,还有由 TypeDescriptor.GetProperties(...) 公开的 ComponentModel - 它允许动态运行时属性(反射在编译时固定)。
        • 建议:扩展答案以涵盖受保护/私有/静态/继承的属性。
        • 您显示的 foreach 语句甚至可以在您想要获取属性的类中工作:)
        • @Tadej 你的目标是什么框架?如果您使用的是 .NET 核心,则需要确保引用了 using System.Reflection 指令和 System.Reflection.TypeExtensions 包 - 这通过扩展方法提供了缺少的 API 表面
        • @HarryPehkonen,我认为您的示例不是财产;它是一个字段,因此您可以使用 foo.GetType().GetFields() 提取所有信息
        【解决方案10】:

        您可以将System.Reflection 命名空间与Type.GetProperties() 方法一起使用:

        PropertyInfo[] propertyInfos;
        propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);
        

        【讨论】:

          【解决方案11】:

          您可以使用反射。

          Type typeOfMyObject = myObject.GetType();
          PropertyInfo[] properties =typeOfMyObject.GetProperties();
          

          【讨论】:

            猜你喜欢
            • 2020-02-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-02-27
            • 1970-01-01
            • 2021-03-26
            • 2013-11-06
            相关资源
            最近更新 更多