Get properties of a Dynamic Type

老子叫甜甜 提交于 2020-08-04 08:08:08

问题


I would like to know how to get the properties of my dynamic type.

This is the function to get the List,

var result = _files.GetFileContent(reportId).Result;

As example I get an object returned like this :

When I open it, you can see the properties I have :

The Idea is that I never know the properties. They can change over time. So I want a list which is filled with all the properties. So I can dynamically use them.

How Can I get the properties from the first item (ChargesDelta_DIFF_5, ChargesEfile_RIGHT,ChargesGecep_LEFT, etc)?


回答1:


You can use reflection to get the properties out and convert it to a dictionary:

dynamic v = new { A = "a" };

Dictionary<string, object> values = ((object)v)
                                     .GetType()
                                     .GetProperties()
                                     .ToDictionary(p => p.Name, p => p.GetValue(v));



回答2:


If someone is still struggling with this (as I did), this might be useful.

Let's say data is the dynamic you want to list all properties from:

This worked for me

using System.ComponentModel;

...

dynamic data = new {
    value1 = 12,
    value2 = "asdasd",
    value3 = 98,
    value4 = "pgiwfj",
};

foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(data))
{
    Console.WriteLine("PROP: " + prop.Name);
}

...

Then it would output:

  • PROP: value1
  • PROP: value2
  • PROP: value3
  • PROP: value4

Source: https://social.msdn.microsoft.com/Forums/vstudio/en-US/251e4f3d-ce90-444a-af20-36bc11864eca/how-to-get-list-of-properties-of-dynamic-object-?forum=csharpgeneral



来源:https://stackoverflow.com/questions/41613558/get-properties-of-a-dynamic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!