using System; using System.Collections.Generic; using CommonLang; using System.Reflection; using CommonLang.Property; namespace CommonLang.Property { public class FieldManager { private HashMap> AllMaps = new HashMap>(); public void AddFieldsMap(FieldsMap fm) { HashMap submap = AllMaps.Get(fm.ObjectType); if (submap == null) { submap = new HashMap(); AllMaps.Add(fm.ObjectType, submap); } submap.Put(fm.FieldType, fm); } public FieldsMap GetFields(Type objectType, Type fieldType) { HashMap submap = AllMaps.Get(objectType); if (submap != null) { return submap.Get(fieldType); } return null; } } public class FieldsMap { public readonly Type ObjectType; public readonly Type FieldType; public readonly List CompatibilityTypes = new List(); public readonly List ListFields = new List(); private HashMap fieldmap = new HashMap(); public FieldsMap(Type objType, Type fieldType, params Type[] compatibilityTypes) { this.ObjectType = objType; this.FieldType = fieldType; this.CompatibilityTypes.Add(fieldType); this.CompatibilityTypes.AddRange(compatibilityTypes); foreach (FieldInfo ff in ObjectType.GetFields()) { if (CompatibilityTypes.Contains(ff.FieldType)) { MemberDescAttribute fda = new MemberDescAttribute(ff); fieldmap.Put(ff.Name, fda); ListFields.Add(fda); } } foreach (PropertyInfo ff in ObjectType.GetProperties()) { if (CompatibilityTypes.Contains(ff.PropertyType)) { MemberDescAttribute fda = new MemberDescAttribute(ff); fieldmap.Put(ff.Name, fda); ListFields.Add(fda); } } foreach (MethodInfo ff in ObjectType.GetMethods()) { if (ff.GetParameters().Length == 0) { if (CompatibilityTypes.Contains(ff.ReturnType)) { MemberDescAttribute fda = new MemberDescAttribute(ff); fieldmap.Put(ff.Name, fda); ListFields.Add(fda); } } } ListFields.Sort(); } public MemberDescAttribute GetFieldDesc(string fieldName) { return fieldmap.Get(fieldName); } public T GetValue(object owner, string fieldName) { MemberDescAttribute desc = fieldmap.Get(fieldName); if (desc != null) { var dv = desc.GetValue(owner); return (T)Convert.ChangeType(dv, typeof(T)); } return default(T); } public void SetValue(object owner, string fieldName, object value) { MemberDescAttribute desc = fieldmap.Get(fieldName); if (desc != null) { var dv = Convert.ChangeType(value, desc.FieldType); desc.SetValue(owner, dv); } } } }