Welcome 微信登录

首页 / 网页编程 / ASP.NET / 对象属性之间的相互赋值

对象属性之间的相互赋值2013-11-28 博客园 JasenKin(一)前言

当不同命名空间下的两个类具有相同的属性,并且需要进行相互赋值时,如下图中的 Jasen.Core.Info类的实例与Jasen.Core.Test.Info类的实例需要相互赋值时,按照一般的思路直接赋值就可 以了。通常,这种情况在调用Web Service的时候比较常见。当需要转换的类很多时,亦或者需要转换的属性 很多时,我们就需要根据一定的规则来对这种场景来进行设计了,谁也不会傻布拉吉的一个一个属性的去给对 象赋值。

(二)ObjectMapper 类负责对象之间相对应的属性间的赋值

/// <summary>/// /// </summary>public class ObjectMapper{/// <summary>/// /// </summary>/// <param name="sourceType"></param>/// <param name="targetType"></param>/// <returns></returns>public static IList<PropertyMapper> GetMapperProperties(Type sourceType, Type targetType){var sourceProperties = sourceType.GetProperties();var targetProperties = targetType.GetProperties();return (from s in sourcePropertiesfrom t in targetPropertieswhere s.Name == t.Name && s.CanRead && t.CanWrite && s.PropertyType == t.PropertyTypeselect new PropertyMapper{SourceProperty = s,TargetProperty = t}).ToList();} /// <summary>/// /// </summary>/// <param name="source"></param>/// <param name="target"></param>public static void CopyProperties(object source, object target){var sourceType = source.GetType();var targetType = target.GetType();var mapperProperties = GetMapperProperties(sourceType, targetType);for (int index = 0,count=mapperProperties.Count; index < count; index++){var property = mapperProperties[index];var sourceValue = property.SourceProperty.GetValue(source, null);property.TargetProperty.SetValue(target, sourceValue, null);}}}