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

前端 未结 4 474
太阳男子
太阳男子 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:13

    You can use this:

    public IEnumerable<string> GetAllPropertyNames(object o)
    {
        foreach (PropertyInfo propInfo in o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
        yield return propInfo.Name;
    }
    
    0 讨论(0)
  • 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<string>.

    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();
    
    0 讨论(0)
  • 2021-01-29 01:33
    var propNames = foo1.GetType()
                        .GetProperties()
                        .Select(pi => pi.Name)
    
    0 讨论(0)
  • 2021-01-29 01:35

    You could try

    var propertyNames = foo1.GetType()
                       .GetProperties()
                       .Select(x => x.Name).ToList();
    
    0 讨论(0)
提交回复
热议问题