11

可能重复:
C#如何通过反射获取字符串属性的值?

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

4

2 回答 2

39
foreach (PropertyInfo pi in t.GetProperties())
    {
        myDict[pi.Name] = pi.GetValue(data,null)?.ToString();

    }
于 2012-04-25T12:00:08.907 回答
10

这应该做你需要的:

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

于 2012-04-25T12:00:37.817 回答