问题
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