How to get the list of properties of a class?

后端 未结 10 1342
陌清茗
陌清茗 2020-11-21 09:48

How do I get a list of all the properties of a class?

相关标签:
10条回答
  • 2020-11-21 10:40

    I am also facing this kind of requirement.

    From this discussion I got another Idea,

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

    This is also showing the property name.

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

    this showing number of properties.

    Thanks to all. This is nice discussion.

    0 讨论(0)
  • 2020-11-21 10:41

    Reflection; for an instance:

    obj.GetType().GetProperties();
    

    for a type:

    typeof(Foo).GetProperties();
    

    for example:

    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));
    }
    

    Following feedback...

    • To get the value of static properties, pass null as the first argument to GetValue
    • To look at non-public properties, use (for example) GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) (which returns all public/private instance properties ).
    0 讨论(0)
  • 2020-11-21 10:51

    You could use the System.Reflection namespace with the Type.GetProperties() mehod:

    PropertyInfo[] propertyInfos;
    propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);
    
    0 讨论(0)
  • 2020-11-21 10:54

    Try this:

    var model = new MyObject();
    foreach (var property in model.GetType().GetProperties())
    {
        var descricao = property;
        var type = property.PropertyType.Name;
    }
    
    0 讨论(0)
提交回复
热议问题