首页 > 解决方案 > 如何访问对象类型c#的属性?

问题描述

var obj1 = new A()
{
  Name = "abc",
  Id = 1
}

var obj2 = new B()
{
   Place = "XYZ",
   Pincode = 123456
}
var obj3 = new C()
{
   Mark = 100,
   Standard = "Tenth"
}

var myList = new List<object>();
myList .add(obj1);
myList .add(obj2);
myList .add(obj3);

这是我的代码结构。我需要访问myList对象的属性。即)我需要从对象访问属性,如Name, Id, Place, Pincode, Mark,它的相应值。StandardmyList

如何实现?

标签: c#listobjectanonymous-types

解决方案


您可以尝试以下方法。工作代码在这里

public static List<List<string>> GetProperties(List<object> myList) 
{
    //  If you don't want two lists, you can use Dictionary<key, value>
    List<string> props = new List<string>();
    List<string> values = new List<string>();

    foreach (var a in myList)
    {
        if(a == null)
            continue;

        var propsInfo = a.GetType().GetProperties();
        foreach (var prop in propsInfo)
        {
            if(!props.Contains(prop.Name))
            {
                props.Add(prop.Name);
                values.Add(prop.GetValue(a, null).ToString());
            }
        }
    }
    return new List<List<string>> { props, values};
}

推荐阅读