[英]How to pass Object as a generic function parameter?
我需要编写一个 function,它将 Object 作为参数,遍历其属性并将其全部写入控制台。 这是一个例子:
设备.cs
public class Equipment
{
public string SerialNo { get; set; }
public string ModelName { get; set; }
}
人物.cs
public class People
{
public string Name { get; set; }
public string Age{ get; set; }
}
这是我从 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,
});
现在我正在努力编写一个 function,它可以接受任何 object 并将其属性写入控制台。 在这种情况下,我不知道如何正确地将对象传递给 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 拨打:
WriteProps(Equipment, equipment_res)
编辑:下面有一个工作示例,但是当我明确传递名为 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));
}
}
使您的方法通用,然后使用反射( System.Reflection ):
void WriteProps<T>(T obj)
{
foreach (var prop in typeof(T).GetProperties())
{
Console.WriteLine(prop.Name);
Console.WriteLine(prop.GetValue(obj));
}
}
利用:
WriteProps(new People
{
Name = "Test",
Age = "11"
});
WriteProps(new Equipment
{
ModelName = "test",
SerialNo = "test"
});
更新:
我将添加此方法以处理 IEnumerable 对象:
void WritePropsList<T>(IEnumerable<T> objects)
{
foreach (var obj in objects)
{
WriteProps(obj);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.