[英]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.我需要编写一个 function,它将 Object 作为参数,遍历其属性并将其全部写入控制台。 Here is an example:
这是一个例子:
Equipment.cs设备.cs
public class Equipment
{
public string SerialNo { get; set; }
public string ModelName { get; set; }
}
People.cs人物.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:这是我从 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.现在我正在努力编写一个 function,它可以接受任何 object 并将其属性写入控制台。 I don't know how to properly pass objects to function in this case:
在这种情况下,我不知道如何正确地将对象传递给 function:
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: Function 拨打:
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:编辑:下面有一个工作示例,但是当我明确传递名为 object 时。它工作正常,但现在我想让这个 function 更通用:
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 ):使您的方法通用,然后使用反射( 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:我将添加此方法以处理 IEnumerable 对象:
void WritePropsList<T>(IEnumerable<T> objects)
{
foreach (var obj in objects)
{
WriteProps(obj);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.