简体   繁体   中英

How to pass Object as a generic function parameter?

I need to write a function which takes whichever Object as a parameter, iterate through its properties and write it all to the console. Here is an example:

Equipment.cs

    public class Equipment
    {
        public string SerialNo { get; set; }
        public string ModelName { get; set; }
    }

People.cs

    public class People
    {
        public string Name { get; set; }
        public string Age{ get; set; }
    }

Here is example of what I return to above models from API:

   var equipment_res = responseObject?.items?.Select(s => new Equipment
       {
          SerialNo = s.serial_number,
          ModelName = s.model.name,
       });

   var people_res = responseObject?.items?.Select(s => new Equipment
       {
          SerialNo = s.serial_number,
          ModelName = s.model.name,
       });

And now I'm struggling to write a function which can take any object and writes its properties to the console. I don't know how to properly pass objects to function in this case:

        public void WriteProps(Object obj1, Object obj2)
        {
                foreach (Object obj1 in obj2)
                {
                    Object obj1 = new Object();

                    foreach (PropertyInfo p in obj1)
                    {
                        Console.WriteLine(p.Name);
                        Console.WriteLine(p.GetValue(obj1, null));
                    }
                }
        }

Function call:

WriteProps(Equipment, equipment_res)

EDIT: below there's a working example but when I explicitly pass named object. It works fine but now I would like to make this function more genric:

   foreach (Equipment item in equipment)
   {
         Equipment eq = new Equipment();
         eq = item;

         foreach (PropertyInfo p in eq)
         {
             Console.WriteLine(p.Name);
             Console.WriteLine(p.GetValue(eq, null));
         }
   }

make your method generic and then use reflection ( System.Reflection ):

void WriteProps<T>(T obj)
{
    foreach (var prop in typeof(T).GetProperties())
    {
        Console.WriteLine(prop.Name);
        Console.WriteLine(prop.GetValue(obj));
    }
}

Use:

WriteProps(new People
{
    Name = "Test",
    Age = "11"
});
WriteProps(new Equipment
{
    ModelName = "test",
    SerialNo = "test"
});

UPDATE:

I'd add this method to work with IEnumerable objects:

void WritePropsList<T>(IEnumerable<T> objects)
{
    foreach (var obj in objects)
    {
        WriteProps(obj);
    }
}

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