获得一个属性的名称列表中 [英] Getting the name of a property in a list

查看:114
本文介绍了获得一个属性的名称列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例



 公共类MyItems 
{
公共对象的Test1 {搞定;组; }
公共对象的Test2 {搞定;组; }
公共对象Test3的{搞定;组; }
公共对象TEST4 {搞定;组; }
公开名单<对象> ITEMLIST
{
得到
{
返回新的List<对象>
{
的Test1,Test2的,Test3的,TEST4
}
}
}
}

公共无效LoadItems()
{
的foreach(在MyItems.itemList VAR项)
{
//获取项目的名称在这里(ASIN,测试1,Test2的)
}
}

**



我已经试过这与反思.. ASIN typeof运算(MyItems).GetFields()等。但是,这并不正常工作。



我怎样才能找出名为项了? Test1的? Test2的?等等...


解决方案

  VAR测试= typeof运算(MyItems).GetProperties()。选择(C => c.Name); 

上面给你的属性名称的枚举。
如果你想获得在列表中使用属性的名称:

  VAR测试= typeof运算(MyItems) .GetProperties()选择(C => c.Name)。.ToList(); 



编辑:



从你的评论,可能是你正在寻找:

 的foreach(在m.itemList VAR项)
{
变种。测试2 =(item.GetType())的GetProperties()选择(C => c.Name)。
}


Example

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<object> itemList
    {
        get
        {
            return new List<object>
            {
                Test1,Test2,Test3,Test4
            }
        }
    }
}

public void LoadItems()
{
    foreach (var item in MyItems.itemList)
    {
        //get name of item here (asin,  Test1, Test2)
    }
}

**

I have tried this with reflection.. asin typeof(MyItems).GetFields() etc.. but that doesn't work.

How can I find out which name "item" has? Test1? Test2?? etc...

解决方案

 var test = typeof(MyItems).GetProperties().Select(c=>c.Name);

The above will give you an Enumerable of properties name. if you want to get the name of the properties in the list use:

var test = typeof(MyItems).GetProperties().Select(c=>c.Name).ToList();

EDIT:

From your comment, may be you are looking for :

 foreach (var item in m.itemList)
    {
        var test2 = (item.GetType()).GetProperties().Select(c => c.Name);
    }

这篇关于获得一个属性的名称列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆