可能重复:
C# How can I get the value of a string property via Reflection?
public class myClass
{
public int a { get; set; }
public int b { get; set; }
public int c { get; set; }
}
public void myMethod(myClass data)
{
Dictionary<string, string> myDict = new Dictionary<string, string>();
Type t = data.GetType();
foreach (PropertyInfo pi in t.GetProperties())
{
myDict[pi.Name] = //...value appropiate sended data.
}
}
3 properties
的简单课程。我发送这个类的对象。
我如何循环获取所有property names
及其值,例如到一个dictionary
?
答案 0 :(得分:32)
foreach (PropertyInfo pi in t.GetProperties())
{
myDict[pi.Name] = pi.GetValue(data,null)?.ToString();
}
答案 1 :(得分:8)
这应该做你需要的:
MyClass myClass = new MyClass();
Type myClassType = myClass.GetType();
PropertyInfo[] properties = myClassType.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(myClass, null));
}
<强>输出:
姓名:a,价值:0
姓名:b,价值:0
姓名:c,价值:0