C#:如何返回对象的所有属性的名称列表?

我上课了:

public class foo { public IEnumerable stst_soldToALTKN { get; set; } public int sId { get; set; } public string stst_LegalName { get; set; } public string stst_TradeName { get; set; } public string stst_StreetAddress { get; set; } } 

有没有我可以调用的方法,它将返回每个属性的名称列表/ ienumerable ???

例如:

 blah foo1 = new foo(); ienumerable foo1List = GetAllPropertyNames(foo1); foo1List.ToList(); 

结果:’stst_soldToALTKN’,’sId’,’stst_LegalName’,’stst_TradeName’,’stst_StreetAddress’

 var propNames = foo1.GetType() .GetProperties() .Select(pi => pi.Name) 

你可以试试

 var propertyNames = foo1.GetType() .GetProperties() .Select(x => x.Name).ToList(); 

你可以用这个:

 public IEnumerable GetAllPropertyNames(object o) { foreach (PropertyInfo propInfo in o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) yield return propInfo.Name; } 

您可以使用reflection来获取属性列表,并从中选择名称:

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

propertyNames现在是List

顺便说一句,你不需要一个foo实例来实现这一点。 您可以通过以下方式获取其类型:

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