Getting the name of a property in a list

瘦欲@ 提交于 2020-01-01 17:36:28

问题


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...


回答1:


 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);
    }



回答2:


The "name" of the object is neither "Test1", nor "MyItems[0]".

Both those are just references to the object, that is in effect, nameless.

I do not know of any technique in C# that could give you all the references to an object, given an object, so I do not think what you want is possible, the way you want it.




回答3:


You can access the name of properties with this code (see MSDN)

Type myType =(typeof(MyTypeClass));
// Get the public properties.
PropertyInfo[] myPropertyInfo = myType.GetProperties(BindingFlags.Public|BindingFlags.Instance);

for(int i=0;i<myPropertyInfo.Length;i++)
{
    PropertyInfo myPropInfo = (PropertyInfo)myPropertyInfo[i];
    Console.WriteLine("The property name is {0}.", myPropInfo.Name);
    Console.WriteLine("The property type is {0}.", myPropInfo.PropertyType);
}

But right now I don't know any code to access the name of a reference!



来源:https://stackoverflow.com/questions/12142332/getting-the-name-of-a-property-in-a-list

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