C#: how to return a list of the names of all properties of an object?

前端 未结 4 478
太阳男子
太阳男子 2021-01-29 00:48

I have a class:

 public class foo
{
    public IEnumerable stst_soldToALTKN { get; set; }
    public int sId { get; set; }        
    public strin         


        
4条回答
  •  离开以前
    2021-01-29 01:18

    You can use reflection to get a list of the properties and from them, select the name:

    var foo1 = new foo();
    var propertyNames = foo1.GetType()
        .GetProperties(BindingFlags.Public | BindingFlag.Instance)
        .Select(p => p.Name)
        .ToList();
    

    propertyNames will now be a List.

    BTW, you don't need an instance of foo for this to work. You can get its type instead by doing:

    var propertyNames = typeof(foo)
        .GetProperties(BindingFlags.Public | BindingFlag.Instance)
        .Select(p => p.Name)
        .ToList();
    

提交回复
热议问题