如何获得属性名称及其价值? [重复]

时间:2021-01-24 23:48:38

Possible Duplicate:
C# How can I get the value of a string property via Reflection?

可能重复:C#如何通过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.
    }
}

Simple class with 3 properties. I send object of this class. How can I i loop get all property names and its values e.g. to one dictionary?

简单类,有3个属性。我发送这个类的对象。我如何循环获取所有属性名称及其值,例如一本字典?

2 个解决方案

#1


22  

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

    }

#2


6  

This should do what you need:

这应该做你需要的:

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));
}

Output:

输出:

Name: a, Value: 0

名称:a,值:0

Name: b, Value: 0

姓名:b,价值:0

Name: c, Value: 0

名称:c,值:0

#1


22  

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

    }

#2


6  

This should do what you need:

这应该做你需要的:

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));
}

Output:

输出:

Name: a, Value: 0

名称:a,值:0

Name: b, Value: 0

姓名:b,价值:0

Name: c, Value: 0

名称:c,值:0