C#在运行时合并两个对象组合在一起 [英] C# merge two objects together at runtime

查看:1850
本文介绍了C#在运行时合并两个对象组合在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在那里我加载从Excel中一个非常非标准化的记录集的情况。我拉每一行中,并且每次从它创建一个对象。每行可以包含公司和/或客户。

I have a situation where I am loading a very unnormalized record set from Excel. I pull in each row and create the objects from it one at a time. each row could contain a company and / or a client.

我的问题是,多行可以有相同的对象,所以我可能已经创造了它。我做一比较,看它是否已经在列表中。如果是这样,我需要两个对象合并,以确保我没有得到从第二行中的任何新的信息。

My issue is that multiple rows could have the same objects, so I may have already created it. I do a comparison to see if it is already in the list. If so I need to merge the two objects to ensure I have not gained any new information from the second row.

这样:

company   - client   - address   - phone
----------------------------------------
mycompany -          - myaddress - 
mycompnay - myclient -           - myphone

这样的第一行会创建一个公司的对象以myaddress的地址。
第二行会创造另一个对象(按我的规则是相同的公司名称是相同的),这也有一个客户参考和一个电话号码。

so the first row would create a company object with an address of "myaddress". The second row would create another company object (which by my rules is the same company as the name is the same), this also having a client reference and a phone number.

因此,我想知道他们是相同的,但需要确保所有的数据合并到一个对象。

So I would know they are the same but need to ensure all the data is merged into one object.

目前,我正在创建一个工具类这需要两个对象,(一个是初级和其他被合并,因此一个具有优先权,如果有冲突),它通过每个变量,如果有任何分配的值。这是一个有点锅炉板沉重,我希望有可能是一些实用的,我可以利用这样做的手工作业对我来说。

At the moment I am creating a utility class that takes both objects, (one being the primary and the other to be merged, so one has priority if there is a clash), it goes through each variable and assigns the values if there are any. This is a bit boiler plate heavy and I was hoping there might be some utility I could utilize to do the manual work for me.

因为有这个例子已被简化一个公平的一些其他变量,一些基本类型和其他更为复杂的项目。

The example has been simplified as there are a fair few other variables, some basic types and others that are more complex items.

推荐答案

反射会工作。是这样的:

Reflection would work. Something like:

public static void MergeWith<T>(this T primary, T secondary) {
    foreach (var pi in typeof(T).GetProperties()) {
       var priValue = pi.GetGetMethod().Invoke(primary, null);
       var secValue = pi.GetGetMethod().Invoke(secondary, null);
       if (priValue == null || (pi.PropertyType.IsValueType && priValue.Equals(Activator.CreateInstance(pi.PropertyType)))) {
          pi.GetSetMethod().Invoke(primary, new object[]{secValue});
       }
    }
}

这篇关于C#在运行时合并两个对象组合在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆