Exemplo n.º 1
0
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            ASObject aso = value as ASObject;

            object instance = TypeHelper.CreateInstance(destinationType);

            if (instance != null)
            {
                foreach (string memberName in aso.Keys)
                {
                    object val = aso[memberName];
                    //MemberInfo mi = ReflectionUtils.GetMember(destinationType, key, MemberTypes.Field | MemberTypes.Property);
                    //if (mi != null)
                    //    ReflectionUtils.SetMemberValue(mi, result, aso[key]);

                    PropertyInfo propertyInfo = null;
                    try
                    {
                        propertyInfo = destinationType.GetProperty(memberName);
                    }
                    catch (AmbiguousMatchException)
                    {
                        //To resolve the ambiguity, include BindingFlags.DeclaredOnly to restrict the search to members that are not inherited.
                        propertyInfo = destinationType.GetProperty(memberName, BindingFlags.DeclaredOnly | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance);
                    }
                    if (propertyInfo != null)
                    {
                        try
                        {
                            val = TypeHelper.ChangeType(val, propertyInfo.PropertyType);
                            if (propertyInfo.CanWrite && propertyInfo.GetSetMethod() != null)
                            {
                                if (propertyInfo.GetIndexParameters() == null || propertyInfo.GetIndexParameters().Length == 0)
                                {
                                    propertyInfo.SetValue(instance, val, null);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.Message);
                        }
                    }
                    else
                    {
                        FieldInfo fi = destinationType.GetField(memberName, BindingFlags.Public | BindingFlags.Instance);
                        try
                        {
                            if (fi != null)
                            {
                                val = TypeHelper.ChangeType(val, fi.FieldType);
                                fi.SetValue(instance, val);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.Message);
                        }
                    }
                }
            }
            return(instance);
        }