簡體   English   中英

如何遍歷 C# 對象的屬性並更新另一個對象的相應屬性

[英]How to iterate through a C# object's properties and update the corresponding property on another object

我必須對同一類型的對象,一個來源和一個目的地。 我試圖做的是遍歷源對象屬性,如果它有值,則在第二個上更新相應的屬性。 我想我有第一部分:

foreach (PropertyInfo prop in object1.GetType().GetProperties())
{ 
     var val = property.GetValue(object1)
     if (val != null)
     {
         --code to update object2 current prop
     }
}

我認為必須有一種方法可以直接引用 object2 上的屬性,而不必遍歷和比較每個名稱和類型。 無論如何希望如此。

我認為這里沒有反思的必要。 您可以在這里簡單地使用AutoMapper並處理 null 的情況。

public class ABC
{
    public string P1 { get; set; }
    public string P2 { get; set; }
}

var configuration = new MapperConfiguration(cfg => {
    cfg.CreateMap<ABC, ABC>().ForAllMembers(o => o.Condition((src, dest, value) => value != null));
});

Mapper mapper = new Mapper(configuration);

var b1 = new ABC { P1 = null, P2 = "b1p2" };
var b2 = new ABC { P1 = "b2p1", P2 = "b2p2" };

mapper.Map(b1, b2); //It will give you b2.P1 = b2p1 and P2 = b1p2

您正在尋找的功能是SetValue ,如下所示:

prop.SetValue(object2, val);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM