简体   繁体   English

如何从C#中的列表中获取属性键名?

[英]How to Get Properties key names from a List in c#?

If I have a list such as : 如果我有以下列表:

var ListCommandQuery = new List<dynamic> { }; 

ListCommandQuery.Add( 
new { User_ID = "4", User_Name = "jhony" ,    Mobile_Phone = 054175548999} );

and i want to print only the Properties key names not the values 我只想打印属性键名而不是值
so the result will show me : 因此结果将显示给我:

User_ID 
User_Name 
Mobile_Phone 

instead of : 代替 :

4
jhony
054175548999

How that can be done ? 那怎么办?

When using anonymous types you need the type definition 使用匿名类型时,需要类型定义

foreach (var item in listCommandQuery)
{
     foreach (var prop in item.GetType().GetProperties())
     {
              Console.WriteLine(prop.Name);
     }
}

In an anonymous object the names are not keys like in a DynamicObject but actual Properties. 在匿名对象中,名称不是像DynamicObject中的键,而是实际的属性。 The Compiler creates an actual class for you in the background. 编译器会在后台为您创建一个实际的类。 Unlike ExpandoObject where the object is an IDictonery 与ExpandoObject不同,在该对象中,对象是一个符号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM