Skip to main content
 首页 » 编程设计

c#之在 2 个实体之间映射属性值

2024年02月23日17zfyouxi

假设我有 2 个实体实例,A 和 B。我想将每个值从实体 A 映射到实体 B。目前我正在做类似的事情

A.firstprop = B.firstprop; 
A.secondprop = B.secondprop; 

等等。我不确定如何在循环中解决这个问题,所以我想在这方面得到一些帮助。谢谢!

请您参考如下方法:

对于你的问题:如何在循环中解决它就像

        var e1 = new Entity(); 
        var e2 = // Get Entity  
 
        foreach (var p in e1.GetType().GetProperties()) 
        {  
            p.SetValue(e1 , e2.GetType().GetProperty(p.Name ).GetValue(e2 , null) , null ); 
        } 

因此,您可以通过循环将值从 entity2 复制到 entity1