Welcome

首页 / 软件开发 / C# / C#集合对象的属性赋值

C#集合对象的属性赋值2013-11-13(一)前言

继《对象属性之间的相互赋值 》后,关于集合对象属性的赋值,主要可以通过循环遍历集合中的对象来进行属性间的赋值。这些可以运用于不同对象之间、相关属性类似的情况。最常见的是web services与silverlight之间的对象赋值(对象之间的属性值只有一部分是需要的),这样可以减少silverlight对web services的依赖。

(二)具体实现

通过反射将源对象与目标对象之间的属性赋值。源对象的属性名、属性类型必须与目标对象的属性名、属性类型一致,并且源对象的属性必须是可读的,目标对象的属性是可写的(仅针对于需要赋值的属性来说)。具体的源代码如下:

public class ObjectMapper{private static readonly Dictionary<string, IList<PropertyMapper>> _mappers =new Dictionary<string, IList<PropertyMapper>>();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();}public static void CopyProperties<T1, T2>(List<T1> sources, List<T2> targets) where T2:new(){if (sources == null || sources.Count == 0 || targets == null){return;}T2 target;foreach (T1 source in sources){target = new T2();CopyProperties(source, target);targets.Add(target);}}public static void CopyProperties(object source, object target){if (source == null || target == null){return;}var sourceType = source.GetType();var targetType = target.GetType();string key = GetMapperKey(sourceType, targetType);if (!_mappers.ContainsKey(key)){MapperProperties(sourceType, targetType);}var mapperProperties = _mappers[key];SetPropertityValue(source, target, mapperProperties);}private static void SetPropertityValue(object source, object target, IList<PropertyMapper> mapperProperties){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);}}protected static string GetMapperKey(Type sourceType, Type targetType){return string.Format("{0}_{1}", sourceType.FullName,targetType.FullName);}public static void MapperProperties(Type source, Type target){if (source == null || target == null){return;}string key = GetMapperKey(source, target);if (_mappers.ContainsKey(key)){return;}var properties = GetMapperProperties(source, target);_mappers.Add(key, properties);}}