C# 如何获取属性名称及其值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10315073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get property name and its value?
提问by Saint
Possible Duplicate:
C# How can I get the value of a string property via Reflection?
可能的重复:
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.
}
}
Simple class with 3 properties. I send object of this class.
How can I i loop get all property namesand its values e.g. to one dictionary?
简单的类 3 properties. 我发送这个类的对象。我怎样才能循环获取所有property names及其值,例如到一个dictionary?
采纳答案by Adrian Iftode
foreach (PropertyInfo pi in t.GetProperties())
{
myDict[pi.Name] = pi.GetValue(data,null)?.ToString();
}
回答by James Hill
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
Name: b, Value: 0
Name: c, Value: 0
名称:a,值:0
名称:b,值:0
名称:c,值:0

