简体   繁体   中英

How to access properties of the object type 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);

This is my code structure. I need to access the properties of the myList object. ie) I need to access the properties like Name , Id , Place , Pincode , Mark , Standard from the myList object and it's corresponding values.

How to achieve it?

You can try something like below. Working code here

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

As I wrote in my comment, usually keeping completely different types in the same collection is wrong. However, that doesn't mean that's always the case, and so assuming you have a good enough reason to do that - here's one option to do it.
Assuming c# 7 or higher, your best option would probably be to (ab)use switch with pattern matching :

foreach(var obj in myList)
{
    switch(obj)
    {
        case A a:
            DoSomethingWithA(a);
            break;
        case B b:
            DoSomethingWithB(b);
            break;
    } 
}

Here is some code I use to compare two objects. I don't know if this is your scenario but I hope it helps you get what you need it for.

protected List<string> GetProperties(List<object> myList) 
{
    List<string> props = 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);
          }
       }
    }
    return props;
}

If you are simply looking to get values out of an object (property values), that is a different story.

foreach (objectType obj in mylist)
{
    someVariable1 = obj.name;
    someVariable2 = obj.Id;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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