获取列表中属性的名称
例
public class MyItems { public object Test1 {get ; set; } public object Test2 {get ; set; } public object Test3 {get ; set; } public object Test4 {get ; set; } public List itemList { get { return new List { Test1,Test2,Test3,Test4 } } } } public void LoadItems() { foreach (var item in MyItems.itemList) { //get name of item here (asin, Test1, Test2) } }
**
我已经尝试过reflection.. asin typeof(MyItems).GetFields()
等..但这不起作用。
如何找出“item”的名称? Test1的? Test2的? 等等…
var test = typeof(MyItems).GetProperties().Select(c=>c.Name);
以上将为您提供一个Enumerable属性名称。 如果要获取列表中属性的名称,请使用:
var test = typeof(MyItems).GetProperties().Select(c=>c.Name).ToList();
编辑:
根据您的评论,您可能正在寻找:
foreach (var item in m.itemList) { var test2 = (item.GetType()).GetProperties().Select(c => c.Name); }
对象的“名称”既不是"Test1"
,也不是"MyItems[0]"
。
这两者都只是对象的引用,实际上是无名的。
我不知道C#中的任何技术可以给你一个对象的所有引用,给定一个对象,所以我不认为你想要的是什么,你想要的方式。
您可以使用此代码访问属性的名称(请参阅MSDN )
Type myType =(typeof(MyTypeClass)); // Get the public properties. PropertyInfo[] myPropertyInfo = myType.GetProperties(BindingFlags.Public|BindingFlags.Instance); for(int i=0;i
但是现在我不知道任何代码来访问引用的名称 !