【问题标题】:How to get property name and its value? [duplicate]如何获取属性名称及其值? [复制]
【发布时间】:2012-05-06 02:28:00
【问题描述】:

可能重复:
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

【问题讨论】:

  • 我已经看到这个问题回答了很多次了:(stackoverflow.com/questions/987982/…
  • @daryal 然后将问题链接为副本并投票关闭?
  • 顺便说一句,.Net 中有一些命名约定

标签: c# loops properties


【解决方案1】:
foreach (PropertyInfo pi in t.GetProperties())
    {
        myDict[pi.Name] = pi.GetValue(data,null)?.ToString();

    }

【讨论】:

  • @AdrianIftode,看起来我们都有一个(包括 OP)。我投票赞成你来补偿。
  • data可以做扩展吗?
  • @Demodave,可能是的,取决于你想要什么。是否要根据myClass 类型的对象的属性创建字典?
  • 如果你有一个空值,当你调用 ToString() 时它会抛出一个异常,所以你应该把它改成 pi.GetValue(data,null) != null ? pi.GetValue(data,null).ToString() : "";
【解决方案2】:

这应该可以满足您的需要:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2018-06-08
    • 1970-01-01
    相关资源
    最近更新 更多