如何获得属性名称及其价值?

Sai*_*int 10 c# loops properties

可能重复:
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.
    }
}
Run Code Online (Sandbox Code Playgroud)

简单的课程3 properties.我发送这个类的对象.我如何循环获取所有property names及其值,例如一个dictionary

Adr*_*ode 35

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

    }
Run Code Online (Sandbox Code Playgroud)


Jam*_*ill 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));
}
Run Code Online (Sandbox Code Playgroud)

输出:

名称:a,值:0

名称:b,值:0

名称:c,值:0