简体   繁体   中英

Merging two objects containing properties into one object

If I have two objects, foo and bar , delared using object initializer syntax...

object foo = new { one = "1", two = "2" };

object bar = new { three = "3", four = "4" };

Is it possible to combine these into a single object, which would look like this...

object foo = new { one = "1", two = "2", three = "3", four = "4" };

No, you can't do this. You've got two separate types at compile-time, but you'd need a third type at execution time, to contain the union of properties.

I mean, you could create a new assembly with the relevant new type in... but then you wouldn't be able to reference it "normally" from your code anyway.

As others have said, it's not convenient to do what you describe but if you just want to do some processing on the combined properties:

Dictionary<string, object> GetCombinedProperties(object o1, object o2) {
    var combinedProperties = new Dictionary<string, object>();
    foreach (var propertyInfo in o1.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
        combinedProperties.Add(propertyInfo.Name, propertyInfo.GetValue(o1, null));
    foreach (var propertyInfo in o2.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
        combinedProperties.Add(propertyInfo.Name, propertyInfo.GetValue(o2, null));
    return combinedProperties;
}

Assuming there are no naming conflicts, its possible using reflection to read the properties of the objects and merge it into a single type, but you'd not be able to access this type directly in your code without performing reflection on it as well.

In 4.0, with the intruduction of the dynamic keyword, it would be possible to reference the dynamic type in code considerably easier. It doesn't make it a better solution, mind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM