C# 获取对象的所有属性
我有这样的目标:C# 获取对象的所有属性,c#,C#,我有这样的目标: some_object foreach (property in some_object) //output the property 此对象大约有1000个属性 我想循环浏览每一个属性,如下所示: some_object foreach (property in some_object) //output the property 有没有一个简单的方法可以做到这一点 using System.Reflection; // reflection namespace
some_object
foreach (property in some_object)
//output the property
此对象大约有1000个属性
我想循环浏览每一个属性,如下所示:
some_object
foreach (property in some_object)
//output the property
有没有一个简单的方法可以做到这一点
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);
}
来源:您使用反射
// 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();
}
甚至有一篇文章描述了如何做你想做的事:-
您可以使用反射
// 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个属性的对象的问题。如果需要以下选项之一,请选择最适合您的选项: 反射: 动态类型:
尽管有人已经指出,拥有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();
在基本类型中,深度搜索道具的更好版本
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));
}
公共静态IEnumerable GetAllProperties(类型t)
{
如果(t==null)
返回可枚举的.Empty();
BindingFlags flags=BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
返回t.GetProperties(flags).Union(GetAllProperties(t.BaseType));
}
林克之神现在正在哭泣……你检查过这些答案了吗:这是一个奇妙而简单的解决方案。自动处理所有子对象,而不必担心递归或自己获取所有属性。