我需要撰寫一個函式,它將任何物件作為引數,遍歷其屬性并將其全部寫入控制臺。這是一個例子:
設備.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,
});
現在我正在努力撰寫一個可以接受任何物件并將其屬性寫入控制臺的函式。在這種情況下,我不知道如何正確地將物件傳遞給函式:
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));
}
}
}
函式呼叫:
WriteProps(Equipment, equipment_res)
編輯:下面有一個作業示例,但是當我明確傳遞命名物件時。它作業正常,但現在我想讓這個函式更通用:
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));
}
}
uj5u.com熱心網友回復:
使您的方法通用,然后使用反射(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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/442881.html
