c#获取对象的所有属性

l--*_*''' 39 c#

我有这样的对象:

some_object
Run Code Online (Sandbox Code Playgroud)

这个对象有1000个属性.

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

foreach (property in some_object)
//output the property
Run Code Online (Sandbox Code Playgroud)

是否有捷径可寻?

Chr*_*ley 60

你可以使用反射.

// 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();
}
Run Code Online (Sandbox Code Playgroud)

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


Des*_*tar 25

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


Bra*_*one 7

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);
}
Run Code Online (Sandbox Code Playgroud)

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

  • Linq众神正在哭泣...... (17认同)