c#获取对象的所有属性

我有这样的对象:

some_object 

这个对象有1000个属性。

我想循环遍历每个属性,如下所示:

 foreach (property in some_object) //output the property 

是否有捷径可寻?

你可以使用reflection。

 // Get property array var properties = GetProperties(some_object); foreach (var p in properties) { string name = p.Name; var value = p.GetValue(some_object, null); } private static PropertyInfo[] GetProperties(object obj) { return obj.GetType().GetProperties(); } 

但是,这仍然无法解决具有1000个属性的对象的问题。

在这种情况下,您可以使用的另一种方法是将对象转换为JSON对象。 JSON.NET库使这很容易,几乎任何对象都可以用JSON表示。 然后,您可以将对象属性作为名称/值对循环。 这种方法对于包含其他对象的复合对象非常有用,因为您可以在树状环境中循环它们。

 MyClass some_object = new MyClass() { PropA = "A", PropB = "B", PropC = "C" }; JObject json = JObject.FromObject(some_object); foreach (JProperty property in json.Properties()) Console.WriteLine(property.Name + " - " + property.Value); Console.ReadLine(); 
 using System.Reflection; // reflection namespace // get all public static properties of MyClass type PropertyInfo[] propertyInfos; propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public | BindingFlags.Static); // sort properties by name Array.Sort(propertyInfos, delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2) { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); }); // write property names foreach (PropertyInfo propertyInfo in propertyInfos) { Console.WriteLine(propertyInfo.Name); } 

资料来源: http : //www.csharp-examples.net/reflection-property-names/

您需要以下其中一项,选择最适合您的方式:

反思: http //msdn.microsoft.com/en-us/library/136wx94f.aspx

动态类型: http //msdn.microsoft.com/en-us/library/dd264741.aspx

虽然有人已经指出,具有1000个属性的类是代码气味。 你可能想要一本字典或集合,

你使用reflection。

甚至有一篇文章描述了如何做你想做的事:

http://geekswithblogs.net/shahed/archive/2006/11/19/97548.aspx

更好的版本的深度搜索道具也在基本类型

 public static IEnumerable GetAllProperties(Type t) { if (t == null) return Enumerable.Empty(); BindingFlags flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly; return t.GetProperties(flags).Union(GetAllProperties(t.BaseType)); }