來源
ASP.NET Starter Kits 的 Portal 專案。
用途
以泛型集合為中介,做資料庫欄位及物件屬性之映射。
原始碼
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Reflection; namespace SybaseUtility { public static class DataMapper { public static void SetPropertyValue(object target, string propertyName, object value) { PropertyInfo propertyInfo = target.GetType().GetProperty(propertyName); if (value == null) propertyInfo.SetValue(target, value, null); else { Type pType = GetPropertyType(propertyInfo.PropertyType); Type vType = GetPropertyType(value.GetType()); if (pType.Equals(vType)) { // types match, just copy value propertyInfo.SetValue(target, value, null); } else { // types don't match, try to coerce if (pType.Equals(typeof(Guid))) propertyInfo.SetValue(target, new Guid(value.ToString()), null); else if (pType.IsEnum && vType.Equals(typeof(string))) propertyInfo.SetValue(target, Enum.Parse(pType, value.ToString()), null); else propertyInfo.SetValue(target, Convert.ChangeType(value, pType), null); } } } public static PropertyInfo[] GetSourceProperties(Type sourceType) { List<PropertyInfo> result = new List<PropertyInfo>(); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(sourceType); foreach (PropertyDescriptor item in props) if (item.IsBrowsable) result.Add(sourceType.GetProperty(item.Name)); return result.ToArray(); } /// <summary> /// Returns a property's type, dealing with /// Nullable(Of T) if necessary. /// </summary> /// <param name="propertyType">Type of the /// property as returned by reflection.</param> private static Type GetPropertyType(Type propertyType) { Type type = propertyType; if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>))) return Nullable.GetUnderlyingType(type); return type; } } }