可能重复:
Enumerating through an object's properties (string) in C#
我可以使用反射来枚举对象的所有属性名称和值吗?
答案 0 :(得分:3)
可能如下所示
假设有一个对象strList
PropertyInfo[] info = strList.GetType().GetProperties();
Dictionary<string, object> propNamesAndValues = new Dictionary<string, object>();
foreach (PropertyInfo pinfo in info)
{
propNamesAndValues.Add(pinfo.Name, pinfo.GetValue(strList, null));
}
答案 1 :(得分:1)
试试这个
var properties = myObj.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public);
var propertyNames = properties.Select(p => p.Name);
var propertyValues = properties.Select(p => p.GetValue(myObj, null));
答案 2 :(得分:0)
尝试使用以下内容:
MyClass aClass = new MyClass();
Type t = aClass.GetType();
PropertyInfo[] pi = t.GetProperties();
foreach (PropertyInfo prop in pi)
Console.WriteLine("Prop: {0}", prop.Name);
希望它会对你有所帮助。