可以使用反射:
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);
}
然而,反思是非常慢得多,不是代碼。如果您需要良好的性能,您可以查看Fasterflect項目,該項目從反射信息動態生成IL代碼。
將它們投射到'dynamic'。 – Steven 2010-08-09 07:01:23