2011-06-22 59 views
26

的所有属性我有对象是这样的:C#获取一个对象

some_object 

此物体具有像1000级的特性。

我想通过这样的每个属性的循环:

foreach (property in some_object) 
//output the property 

有一种简单的方法来做到这一点?

+1

你检查这些问题的答案:http://stackoverflow.com/questions/737151/how-to-get-the-list-属性的 – Guildencrantz

回答

39

您可以使用反射。

// 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个属性的对象的问题。

6
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/

+14

林奇众神正在哭... – Blindy

16

您可以在这种情况下使用的另一种方法是将对象转换为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(); 
+0

这是一个梦幻般和简单的解决方案。自动处理所有子对象,无需担心递归或自己抓取所有属性。 – mppowe

1

更好的版本也基本类型

public static IEnumerable<PropertyInfo> GetAllProperties(Type t) 
{ 
    if (t == null) 
    return Enumerable.Empty<PropertyInfo>(); 

    BindingFlags flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly; 
    return t.GetProperties(flags).Union(GetAllProperties(t.BaseType)); 
}