【发布时间】:2018-05-09 02:29:01
【问题描述】:
我得到 2 个类型为“Shipment”的对象(“Shipment1”和“Shipment2”),并且必须读取它们的每个值。如果 Shipment1 的值为 NULL/空,我想查看 Shipment2 的相同值,如果值不是 NULL/空,我必须将其复制到 Shipment1。 我试图用反射遍历我的对象,但是嵌套的对象“Consignor”、“Consignee”、“Invoices”让我失败了。我希望你能帮助我。 我有以下简化的类结构:
public class Shipment
{
public int Id { get; set; }
public Address Consignor { get; set; }
public Address Consignee { get; set; }
public IEnumerable<Invoice> Invoices{ get; set; }
}
public class Address
{
public string Name { get; set; }
public string Street{ get; set; }
public string Zip { get; set; }
public string City{ get; set; }
public string Country{ get; set; }
}
public class Invoice
{
public IEnumerable<Item> Items{ get; set; }
}
public class Item
{
public string Description{ get; set; }
public int Amount { get; set; }
}
我试过这样。它适用于货运的顶级属性,但不适用于发货人、收货人、发票等。
foreach (PropertyInfo info1 in shipment1.GetType().GetProperties())
{
var datatype = info1.PropertyType;
switch (datatype.Name.ToLower())
{
case "string":
if (!string.IsNullOrEmpty((string)info1.GetValue(shipment1)))
{
string value= (string)info1.GetValue(shipment1);
string name = info1.Name;
Type type = input.GetType();
PropertyInfo info2 = shipment2.GetType().GetProperty(name);
if (string.IsNullOrEmpty((string)info2.GetValue(shipment2)))
{
info2.SetValue(shipment2, value, null);
}
}
break;
case "integer":
// and so on
}
}
【问题讨论】:
-
当
shipment1有一个Address的值为Zipe,但Street没有值,而shipment2有一个Address时,你决定做什么?Street的值和Zipe的不同值?盲目抄袭?在这种情况下,我认为地址没有任何意义。 -
是的,你是对的,这没有任何意义。在我的用例中,地址属性不会为空。这只是一个简化的类结构,我正在寻找一种遍历每个属性、嵌套对象等的算法。
-
循环属性的代码在哪里?
-
我添加了我的迭代示例
标签: c# loops reflection nested