C# Objects with the same properties conversion [duplicate]
Possible Duplicate:
How to copy value from class X to class Y with the same property name in c#?
C# 4.0
If i have N numbers of POCO objects with the same properties (the same names and types) I want to convert them one to another. They dont have any parent relations, the just POCO.
I may type converted function to copy just properties values from one to another:
obj1.a = obj1.a; obj2.a = obj2.a; ...
but it is very boring to do this and especially in examples when i have many properties in object开发者_开发百科s. May by someone may suggest more clever way of doing this?
You can use Reflection like Tcks desribes it, or you can use AutoMapper
http://automapper.codeplex.com/
With AutoMapper you have an easy to use Mapper. Which is based on Convention. Also you can do more complex things if you need them. See the examples.
You can use the reflection:
object obj1 = GetObject(1);
object obj2 = GetObject(2);
Type type1 = obj1.GetType();
Type type2 = obj2.GetType();
var properties = (from p1 in type1.GetProperties( BindingFlags.Instance | BindingFlags.Public )
where p1.CanRead && p1.CanWrite
from p2 in type2.GetProperties( BindingFlags.Instance | BindingFlags.Public )
where p2.CanRead && p2.CanWrite
where p1.Name == p2.Name && p1.PropertyType = p2.PropertyType
select new { Property1 = p1, Property2 = p2 }).ToList();
foreach( var props in properties ) {
object value1 = props.Property1.GetValue( obj1, null );
props.Property2.SetValue( obj2, value1, null );
}
However, the reflection is much much slower, than the code. If you need good performance, you can look at Fasterflect project, which dynamicly generates IL code from reflection infos.
精彩评论