Esempio n. 1
0
		public void EmitDeserialize(PropertyInfo property, ref EmitHelper deserializeEmit)
		{
			var propertyType = property.PropertyType;
			var propertyNullLabel = deserializeEmit.DefineLabel();
			var propertyNotNullLabel = deserializeEmit.DefineLabel();
			var propertyInstanceType = deserializeEmit.DeclareLocal(typeof(Type));
			var indexLocal = deserializeEmit.DeclareLocal(typeof(int));
			var objectExistsLocal = deserializeEmit.DefineLabel();
			var objectNotExistsLocal = deserializeEmit.DefineLabel();
			deserializeEmit
				.ldarg_1
				.call(typeof(BinaryReader).GetMethod("ReadInt32"))
				.stloc(indexLocal)
				.ldloc(indexLocal)
				.ldc_i4_m1
				.ceq
				.brfalse(propertyNotNullLabel)
				.ldarg_0
				.ldnull
				.call(property.GetSetMethod())
				.br(propertyNullLabel)
				.MarkLabel(propertyNotNullLabel)
				.ldarg_2
				.ldloc(indexLocal)
				.call(typeof(IDictionary<int, object>).GetMethod("ContainsKey", new Type[] { typeof(int) }))
				.brfalse(objectNotExistsLocal)
				.ldarg_0
				.ldarg_2
				.ldloc(indexLocal)
				.call(typeof(IDictionary<int, object>).GetMethod("get_Item", new Type[] { typeof(int) }))
				.castclass(propertyType)
				.call(property.GetSetMethod())
				.br(objectExistsLocal)
				.MarkLabel(objectNotExistsLocal)
				.ldarg_1
				.call(typeof(BinaryReader).GetMethod("ReadString"))
				.call(typeof(Type).GetMethod("GetType", new Type[] { typeof(string) }))
				.stloc(propertyInstanceType)
				.ldarg_0
				.ldloc(propertyInstanceType)
				.call(typeof(Activator).GetMethod("CreateInstance", new Type[] { typeof(Type) }))
				.call(typeof(Converter).GetMethod("Convert", new[] { typeof(object) }))
				.castclass(propertyType)
				.call(property.GetSetMethod())
				.ldarg_2
				.ldloc(indexLocal)
				.ldarg_0
				.call(property.GetGetMethod())
				.call(typeof(IDictionary<int, object>).GetMethod("Add", new[] { typeof(int), typeof(object) }))
				.ldarg_0
				.call(property.GetGetMethod())
				.castclass(typeof(ISerializable))
				.ldarg_1
				.ldarg_2
				.call(typeof(ISerializable).GetMethod("Deserialize", new Type[] { typeof(BinaryReader), typeof(IDictionary<int, object>) }))
				.MarkLabel(objectExistsLocal)
				.MarkLabel(propertyNullLabel);
		}
Esempio n. 2
0
 internal fsMetaProperty(PropertyInfo property) {
     _memberInfo = property;
     StorageType = property.PropertyType;
     JsonName = GetJsonName(property);
     MemberName = property.Name;
     IsPublic = (property.GetGetMethod() != null && property.GetGetMethod().IsPublic) && (property.GetSetMethod() != null && property.GetSetMethod().IsPublic);
     CanRead = property.CanRead;
     CanWrite = property.CanWrite;
 }
        /// <summary>
        /// Initializes a new instance of the PropertyMetadata class from a property member.
        /// </summary>
        public InspectedProperty(PropertyInfo property)
        {
            MemberInfo = property;
            StorageType = property.PropertyType;
            CanWrite = property.GetSetMethod(/*nonPublic:*/ true) != null;
            IsStatic = (property.GetGetMethod(/*nonPublic:*/ true) ?? property.GetSetMethod(/*nonPublic:*/ true)).IsStatic;

            SetupNames();
        }
Esempio n. 4
0
        internal fsMetaProperty(PropertyInfo property) {
            _memberInfo = property;
            StorageType = property.PropertyType;
            MemberName = property.Name;
            IsPublic = (property.GetGetMethod() != null && property.GetGetMethod().IsPublic) &&
                       (property.GetSetMethod() != null && property.GetSetMethod().IsPublic);
            CanRead = property.CanRead;
            CanWrite = property.CanWrite;

            CommonInitialize();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyDescriptor" /> class.
        /// </summary>
        /// <param name="propertyInfo">The property information.</param>
        /// <param name="defaultNameComparer">The default name comparer.</param>
        /// <exception cref="System.ArgumentNullException">propertyInfo</exception>
        public PropertyDescriptor(PropertyInfo propertyInfo, StringComparer defaultNameComparer)
            : base(propertyInfo, defaultNameComparer)
		{
			if (propertyInfo == null) throw new ArgumentNullException("propertyInfo");

			this.propertyInfo = propertyInfo;

			getMethod = propertyInfo.GetGetMethod(true);
			if (propertyInfo.CanWrite && propertyInfo.GetSetMethod(!IsPublic) != null)
			{
				setMethod = propertyInfo.GetSetMethod(!IsPublic);
			}
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyDescriptor"/> class.
        /// </summary>
        /// <param name="propertyInfo">The property information.</param>
        public PropertyDescriptor(PropertyInfo propertyInfo)
            : base(propertyInfo)
        {
            if (propertyInfo == null) throw new ArgumentNullException("propertyInfo");

            this.propertyInfo = propertyInfo;

            getMethod = propertyInfo.GetGetMethod(false);
            if (propertyInfo.CanWrite && propertyInfo.GetSetMethod(false) != null)
            {
                setMethod = propertyInfo.GetSetMethod(false);
            }
        }
Esempio n. 7
0
        public static Action<object, object> CreatePropertySetter(PropertyInfo property)
        {
            if (property == null)
                throw new ArgumentNullException("property");
            if (!property.CanWrite)
                return null;

            MethodInfo setMethod = property.GetSetMethod();
            DynamicMethod dm = new DynamicMethod("PropertySetter", null, new Type[] { typeof(object), typeof(object) }, property.DeclaringType, true);

            ILGenerator il = dm.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            Type type = property.PropertyType;
            if (type.GetTypeInfo().IsValueType)
                il.Emit(OpCodes.Unbox_Any, type);
            else
                il.Emit(OpCodes.Castclass, type);
            if (!property.DeclaringType.GetTypeInfo().IsValueType)
                il.EmitCall(OpCodes.Callvirt, setMethod, null);
            else
                il.EmitCall(OpCodes.Call, setMethod, null);
            il.Emit(OpCodes.Ret);

            return dm.CreateDelegate(typeof(Action<object, object>)) as Action<object, object>;
        }
 public StepArgument(PropertyInfo member, object declaringObject)
 {
     Name = member.Name;
     _get = () => member.GetGetMethod(true).Invoke(declaringObject, null);
     _set = o => member.GetSetMethod(true).Invoke(declaringObject, new[] { o });
     ArgumentType = member.PropertyType;
 }
Esempio n. 9
0
 /// <summary> 表示一个可以获取或者设置其内容的对象属性
 /// </summary>
 /// <param name="property">属性信息</param>
 public ObjectProperty(PropertyInfo property)
 {
     Field = false;
     MemberInfo = property; //属性信息
     OriginalType = property.PropertyType;
     var get = property.GetGetMethod(true); //获取属性get方法,不论是否公开
     var set = property.GetSetMethod(true); //获取属性set方法,不论是否公开
     if (set != null) //set方法不为空
     {
         CanWrite = true; //属性可写
         Static = set.IsStatic; //属性是否为静态属性
         IsPublic = set.IsPublic;
     }
     if (get != null) //get方法不为空
     {
         CanRead = true; //属性可读
         Static = get.IsStatic; //get.set只要有一个静态就是静态
         IsPublic = IsPublic || get.IsPublic;
     }
     ID = System.Threading.Interlocked.Increment(ref Literacy.Sequence);
     UID = Guid.NewGuid();
     Init();
     TypeCodes = TypeInfo.TypeCodes;
     Attributes = new AttributeCollection(MemberInfo);
     var mapping = Attributes.First<IMemberMappingAttribute>();
     if (mapping != null)
     {
         MappingName = mapping.Name;
     }
 }
        public static SetValueDelegate CreatePropertySetter(PropertyInfo property)
        {
            if (property == null) {
                throw new ArgumentNullException("property");
            }

            if (!property.CanWrite) {
                return null;
            }

            var setMethod = property.GetSetMethod();

            var dm = new DynamicMethod("PropertySetter", null, new Type[] { typeof(object), typeof(object) }, property.DeclaringType, true);
            ILGenerator il = dm.GetILGenerator();

            if (!setMethod.IsStatic) {
                il.Emit(OpCodes.Ldarg_0);
            }
            il.Emit(OpCodes.Ldarg_1);

            EmitCastToReference(il, property.PropertyType);

            if (!setMethod.IsStatic && !property.DeclaringType.IsValueType) {
                il.EmitCall(OpCodes.Callvirt, setMethod, null);
            } else {
                il.EmitCall(OpCodes.Call, setMethod, null);
            }

            il.Emit(OpCodes.Ret);

            return (SetValueDelegate)dm.CreateDelegate(typeof(SetValueDelegate));
        }
Esempio n. 11
0
        static Action<object, object> GetSetMethod(PropertyInfo property, bool includeNonPublic)
        {
            ParameterExpression instance = Expression.Parameter(typeof(object), "instance");
            ParameterExpression value = Expression.Parameter(typeof(object), "value");

            // value as T is slightly faster than (T)value, so if it's not a value type, use that
            UnaryExpression instanceCast;
            #if !NETFX_CORE
            if (property.DeclaringType.IsValueType)
            #else
            if (property.DeclaringType.GetTypeInfo().IsValueType)
            #endif
                instanceCast = Expression.Convert(instance, property.DeclaringType);
            else
                instanceCast = Expression.TypeAs(instance, property.DeclaringType);

            UnaryExpression valueCast;
            #if !NETFX_CORE
            if (property.PropertyType.IsValueType)
            #else
            if (property.PropertyType.GetTypeInfo().IsValueType)
            #endif
                valueCast = Expression.Convert(value, property.PropertyType);
            else
                valueCast = Expression.TypeAs(value, property.PropertyType);

            #if !NETFX_CORE
            MethodCallExpression call = Expression.Call(instanceCast, property.GetSetMethod(includeNonPublic), valueCast);
            #else
            MethodCallExpression call = Expression.Call(instanceCast, property.SetMethod, valueCast);
            #endif

            return Expression.Lambda<Action<object, object>>(call, new[] {instance, value}).Compile();
        }
Esempio n. 12
0
        /// <summary>
        /// �����¶���
        /// </summary>
        /// <param name="colAttr">����������</param>
        /// <param name="prop">��֮������������Ϣ</param>
        public PropertyColumn(ColumnMappingAttribute colAttr, PropertyInfo prop)
            : base(colAttr)
        {
            if (prop == null)
            {
                throw new ArgumentNullException();
            }

            this.prop = prop;

            getter = prop.GetGetMethod();
            setter = prop.GetSetMethod();

            if (colAttr.Name == null || colAttr.Name == string.Empty)
                this.Name = prop.Name;
            else
                this.Name = colAttr.Name;

            if (this.DataType == typeof(object))
            {
                throw new OrmLogicException("Not Allowed to declare Object type as basic column");
            }

            if (colAttr.DbType == System.Data.DbType.Object)
            {
                //������������
                this.DbType = DbFunction.BuildDbType(this.DataType);
            }
        }
Esempio n. 13
0
        public static T Copy <T>(this T obj) where T : new()
        {
            if (obj == null)
            {
                return(obj);
            }
            Object targetDeepCopyObj;
            Type   targetType = obj.GetType();

                        //值类型
                        if(targetType.IsValueType == true)
            {
                targetDeepCopyObj = obj;
            }

                        //引用类型
                        else
            {
                targetDeepCopyObj = System.Activator.CreateInstance(targetType);    //创建引用对象
                                System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();

                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        Object fieldValue = field.GetValue(obj);
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, Copy(fieldValue));
                        }
                    }
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;
                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            object propertyValue = myProperty.GetValue(obj, null);
                            if (propertyValue is ICloneable)
                            {
                                myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                            }
                            else
                            {
                                if (propertyValue != null)
                                {
                                    myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);
                                }
                            }
                        }
                    }
                }
            }
            return((T)targetDeepCopyObj);
        }
Esempio n. 14
0
 internal static bool IsInteresting(PropertyInfo pi)
 {
     MethodInfo getter, setter;
     return pi.CanRead && pi.CanWrite &&
         (getter = pi.GetGetMethod()) != null && getter.IsVirtual &&
         (setter = pi.GetSetMethod()) != null && setter.IsVirtual;
 }
        /// <summary>
        /// Gets or creates an injector for the specified property.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <returns>The created injector.</returns>
        public PropertyInjector Create(PropertyInfo property)
        {
            #if NO_SKIP_VISIBILITY
            var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object) });
            #else
            var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object) }, true);
            #endif
            
            ILGenerator il = dynamicMethod.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            EmitUnboxOrCast(il, property.DeclaringType);

            il.Emit(OpCodes.Ldarg_1);
            EmitUnboxOrCast(il, property.PropertyType);

            #if !SILVERLIGHT
            bool injectNonPublic = Settings.InjectNonPublic;
            #else
            const bool injectNonPublic = false;
            #endif // !SILVERLIGHT

            EmitMethodCall(il, property.GetSetMethod(injectNonPublic));
            il.Emit(OpCodes.Ret);

            return (PropertyInjector) dynamicMethod.CreateDelegate(typeof(PropertyInjector));
        }
        private SchemaInfo FromPropertyInfo(PropertyInfo pi)
        {
            if (!this.IsMapped(pi))
                return null;

            Type propertyType = pi.PropertyType;

            bool nullableTypeDetected = propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == CachedTypes.PureNullableType;

            SchemaInfo schema = new SchemaInfo(pi.Name, nullableTypeDetected ? propertyType.GetGenericArguments()[0] : propertyType);

            //NotMapped gibi bir standart
            KeyAttribute keyAtt = pi.GetCustomAttribute<KeyAttribute>();
            if (null != keyAtt)
                schema.IsKey = true;

            if (nullableTypeDetected)
                schema.IsNullable = true;
            else
            {
                if (propertyType.IsClass)
                    schema.IsNullable = true;
                else if (propertyType.IsValueType)
                    schema.IsNullable = false;
            }

            bool hasSetMethod = pi.GetSetMethod() != null;
            if (!hasSetMethod)
                schema.ReadOnly = true;

            this.SetExtendedSchema(schema, pi);

            return schema;
        }
Esempio n. 17
0
        public DynamicPropertyAccessor(PropertyInfo propertyInfo)
        {
            // target: (object)((({TargetType})instance).{Property})

            // preparing parameter, object type
            ParameterExpression instance = Expression.Parameter(
                typeof(object), "instance");

            // ({TargetType})instance
            Expression instanceCast = Expression.Convert(
                instance, propertyInfo.ReflectedType);

            // (({TargetType})instance).{Property}
            Expression propertyAccess = Expression.Property(
                instanceCast, propertyInfo);

            // (object)((({TargetType})instance).{Property})
            UnaryExpression castPropertyValue = Expression.Convert(
                propertyAccess, typeof(object));

            // Lambda expression
            Expression<Func<object, object>> lambda =
                Expression.Lambda<Func<object, object>>(
                    castPropertyValue, instance);

            this.m_getter = lambda.Compile();

            MethodInfo setMethod = propertyInfo.GetSetMethod();
            if (setMethod != null) {
                this.m_dynamicSetter = new DynamicMethodExecutor(setMethod);
            }
        }
Esempio n. 18
0
        /// <summary>
        /// .ctor
        /// </summary>
        /// <param name="owner">Metadata of the owning entity.</param>
        /// <param name="propertyInfo">PropertyInfo of the accessed  entity property.</param>
        public TikEntityPropertyAccessor(TikEntityMetadata owner, PropertyInfo propertyInfo)
        {
            _owner = owner;

            PropertyInfo = propertyInfo;

            //From property code
            PropertyName = propertyInfo.Name;
            PropertyType = propertyInfo.PropertyType;

            //From TikPropertyAttribute attribute
            var propertyAttribute = propertyInfo.GetCustomAttribute<TikPropertyAttribute>(true);
            if (propertyAttribute == null)
                throw new ArgumentException("Property must be decorated by TikPropertyAttribute.", "propertyInfo");
            FieldName = propertyAttribute.FieldName;
            _isReadOnly = (propertyInfo.GetSetMethod() == null) || (!propertyInfo.CanWrite) || (propertyAttribute.IsReadOnly);
            IsMandatory = propertyAttribute.IsMandatory;
            if (propertyAttribute.DefaultValue != null)
                DefaultValue = propertyAttribute.DefaultValue;
            else
            {
                if (PropertyType.IsValueType)
                    DefaultValue = ConvertToString(Activator.CreateInstance(PropertyType)); //default value of value type. for example: (default)int
                else
                    DefaultValue = "";
            }
            UnsetOnDefault = propertyAttribute.UnsetOnDefault;
        }
Esempio n. 19
0
 public PropertyObject(PropertyInfo md)
     : base()
 {
     getter = md.GetGetMethod(true);
     setter = md.GetSetMethod(true);
     info = md;
 }
Esempio n. 20
0
        private static bool IsMatch(PropertyInfo propertyInfo, BindingFlags flags)
        {
            // this methods is heavily used during reflection, so we have traded
            // readablility for performance.

            var mainMethod = propertyInfo.GetGetMethod() ?? propertyInfo.GetSetMethod();
            if (mainMethod == null)
                return false;

            if (flags == Type.BindFlags.AllMembers || flags == Type.BindFlags.DeclaredMembers)
                return true;

            bool incStatic   = (flags & BindingFlags.Static) == BindingFlags.Static;
            bool incInstance = (flags & BindingFlags.Instance) == BindingFlags.Instance;

            if (incInstance == incStatic && !incInstance)
                return false;

            if (incInstance != incStatic)
            {
                bool isStatic = mainMethod.IsStatic;

                if (!((incStatic && isStatic) || (incInstance && !isStatic)))
                    return false;
            }

            bool incPublic    = (flags & BindingFlags.Public) == BindingFlags.Public;
            bool incNonPublic = (flags & BindingFlags.NonPublic) == BindingFlags.NonPublic;

            if (incPublic == incNonPublic)
                return incPublic;

            bool isPublic = mainMethod.IsPublic;
            return (incPublic && isPublic) || (incNonPublic && !isPublic);
        }
 private void BindToProperty(PropertyInfo property)
 {
     if (property.GetSetMethod(true) == null)
     {
         this.MemberAccess = MemberAccess.Create(AccessStrategy.NoSetter, TryToFindFieldNamingStrategy(property));
     }
 }
        public PocoFeatureAttributeDefinition(PropertyInfo propertyInfo, FeatureAttributeAttribute att)
        {
            AttributeName = propertyInfo.Name;
            if (!string.IsNullOrEmpty(att.AttributeName)) AttributeName = att.AttributeName;

            AttributeDescription = att.AttributeDescription;
            
            AttributeType = propertyInfo.PropertyType;
            if (propertyInfo.CanRead)
            {
                _getMethod = propertyInfo.GetGetMethod();
                _static = _getMethod.IsStatic;
            }
            if (propertyInfo.CanWrite)
            {
                _setMethod = propertyInfo.GetSetMethod();
            }
            else
            {
                _readonly = true;
            }
            
            /*
            var att = propertyInfo.GetCustomAttributes(typeof (FeatureAttributeAttribute), true);
            if (att.Length > 0) CorrectByAttribute((FeatureAttributeAttribute)att[0]);
             */

            CorrectByAttribute(att);
        }
Esempio n. 23
0
 /// <summary>
 /// Initialize the structure for a Property
 /// </summary>
 /// <param name="reflectedProperty">Property to import</param>
 public Property(System.Reflection.PropertyInfo reflectedProperty)
     : base(reflectedProperty)
 {
     CanRead   = reflectedProperty.CanRead;
     GetMethod = (CanRead ? reflectedProperty.GetGetMethod(true) : null);
     SetMethod = (CanWrite ? reflectedProperty.GetSetMethod(true) : null);
 }
Esempio n. 24
0
        bool IsAReadWriteProperty(PropertyInfo propertyInfo)
        {
            if (!propertyInfo.GetSetMethod(true).IsPublic || !propertyInfo.GetGetMethod(true).IsPublic)
                throw new InvalidOperationException("Tweakable property {" + propertyInfo.ReflectedType + "." + propertyInfo.Name + "} is of the wrong type (should be public read/write)");

            return true;
        }
Esempio n. 25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CachedPropertyInfo"/> class.
        /// </summary>
        /// <param name="propertyInfo">The property information.</param>
        public CachedPropertyInfo(PropertyInfo propertyInfo)
        {
            Argument.IsNotNull("propertyInfo", propertyInfo);

            PropertyInfo = propertyInfo;

            _publicGetter = new Lazy<bool>(() =>
            {
#if NETFX_CORE || PCL
                var getMethod = propertyInfo.GetMethod;
#else
                var getMethod = propertyInfo.GetGetMethod(false);
#endif

                return getMethod != null && getMethod.IsPublic;
            });

            _publicSetter = new Lazy<bool>(() =>
            {
#if NETFX_CORE || PCL
                var setMethod = propertyInfo.SetMethod;
#else
                var setMethod = propertyInfo.GetSetMethod(false);
#endif

                return setMethod != null && setMethod.IsPublic;
            });
        }
 /// <summary>
 /// Initialize the structure for a Property
 /// </summary>
 /// <param name="property">Property to import</param>
 public PropertyInfo(System.Reflection.PropertyInfo property)
     : base(property)
 {
     CanRead   = property.CanRead;
     GetMethod = (CanRead ? property.GetGetMethod(true) : null);
     SetMethod = (CanWrite ? property.GetSetMethod(true) : null);
 }
		// TODO: NLiblet
#if DEBUG
		public void EmitSetProperty( PropertyInfo property )
		{
			Contract.Assert( property != null );
			Contract.Assert( property.CanWrite );

			this.EmitAnyCall( property.GetSetMethod( true ) );
		}
 public void SetConfiguration( PropertyInfo p, ServiceLogMethodOptions option )
 {
     MethodInfo mG = p.GetGetMethod();
     if( mG != null ) SetConfiguration( mG, option );
     MethodInfo mS = p.GetSetMethod();
     if( mS != null ) SetConfiguration( mS, option );
 }
Esempio n. 29
0
		public static SetPropertyDelegate GetSetPropertyMethod(Type type, PropertyInfo propertyInfo)
		{
			var setMethodInfo = propertyInfo.GetSetMethod(true);
			if (setMethodInfo == null) return null;
			
#if SILVERLIGHT || MONOTOUCH || XBOX
			return (instance, value) => setMethodInfo.Invoke(instance, new[] {value});
#else
			var oInstanceParam = Expression.Parameter(typeof(object), "oInstanceParam");
			var oValueParam = Expression.Parameter(typeof(object), "oValueParam");

			var instanceParam = Expression.Convert(oInstanceParam, type);
			var useType = propertyInfo.PropertyType;

			var valueParam = Expression.Convert(oValueParam, useType);
			var exprCallPropertySetFn = Expression.Call(instanceParam, setMethodInfo, valueParam);

			var propertySetFn = Expression.Lambda<SetPropertyDelegate>
				(
					exprCallPropertySetFn,
					oInstanceParam,
					oValueParam
				).Compile();

			return propertySetFn;
#endif			
		}
Esempio n. 30
0
    public static object Copy(object obj)
    {
        System.Object targetDeepCopyObj;
        Type          targetType = obj.GetType();

        //值类型
        if (targetType.IsValueType == true)
        {
            targetDeepCopyObj = obj;
        }
        //引用类型
        else
        {
            targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //创建引用对象
            System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();

            foreach (System.Reflection.MemberInfo member in memberCollection)
            {
                if (member.MemberType == System.Reflection.MemberTypes.Field)
                {
                    System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                    System.Object fieldValue          = field.GetValue(obj);
                    try
                    {
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, Copy(fieldValue));
                        }
                    }
                    catch (Exception e)
                    {
                        LogMgr.UnityError(e.ToString());
                    }
                }
                else if (member.MemberType == System.Reflection.MemberTypes.Property)
                {
                    System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;
                    MethodInfo info = myProperty.GetSetMethod(false);
                    if (info != null)
                    {
                        object propertyValue = myProperty.GetValue(obj, null);
                        if (propertyValue is ICloneable)
                        {
                            myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                        }
                        else
                        {
                            myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);
                        }
                    }
                }
            }
        }
        return(targetDeepCopyObj);
    }
Esempio n. 31
0
 public override void DecorateProperty(object obj, PropertyInfo propertyInfo)
 {
     if (propertyInfo.CanWrite)
     {
         Type returnType = propertyInfo.GetSetMethod().GetParameters()[0].ParameterType;
         Object instance = Decorator.InitializeType<Object>(returnType, null);
         Decorator.Decorate<Object>(instance);
         propertyInfo.GetSetMethod().Invoke(obj, new Object[1] { instance });
     }
     else if(propertyInfo.CanRead)
     {
         Type returnType = propertyInfo.GetGetMethod().ReturnType;
         Object instance = Decorator.InitializeType<Object>(returnType, null);
         Decorator.Decorate<Object>(instance);
         obj.GetType().GetMethod("set___" + propertyInfo.Name).Invoke(obj, new Object[1]{instance});
     }
 }
Esempio n. 32
0
 public EnumPropertyField(object instance, string name)
 {
     this.instance = instance;
     this.name     = name;
     System.Reflection.PropertyInfo info = instance.GetType().GetProperty(name);
     setter = info.GetSetMethod();
     getter = info.GetGetMethod();
 }
Esempio n. 33
0
 public ClassAccessor(PropertyInfo property)
 {
     this.Name = property.Name;
     this.PropertyType = property.PropertyType;
     this.IsPrimaryKey = false;
     this.getter = createGetter(property.GetGetMethod());
     this.setter = createSetter(property.GetSetMethod());
 }
 public PropertyInterceptionArgs(object instance, PropertyInfo property, object value)
     : base(instance, property, value)
 {
     var getter = property.GetGetMethod(nonPublic: true);
     if (getter != null) _getter = DelegateFactory.CreateGetter(instance, getter);
     var setter = property.GetSetMethod(nonPublic: true);
     if (setter != null) _setter = DelegateFactory.CreateSetter(instance, setter);
 }
Esempio n. 35
0
        public static object Copy(this object obj)
        {
            if (obj == null)
            {
                return(null);
            }
            Object targetDeepCopyObj;
            Type   targetType = obj.GetType();

            if (targetType.IsValueType == true)
            {
                targetDeepCopyObj = obj;
            }
            else
            {
                targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //创建引用对象
                System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();

                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    if (member.GetType().GetProperty("Item") != null)
                    {
                        continue;
                    }
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        Object fieldValue = field.GetValue(obj);
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, fieldValue.Copy());
                        }
                    }
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;
                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            object propertyValue = myProperty.GetValue(obj, null);
                            if (propertyValue is ICloneable)
                            {
                                myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                            }
                            else
                            {
                                myProperty.SetValue(targetDeepCopyObj, propertyValue.Copy(), null);
                            }
                        }
                    }
                }
            }
            return(targetDeepCopyObj);
        }
Esempio n. 36
0
        public static void Update(object _old, object _new)
        {
            try
            {
                System.Reflection.MemberInfo[] memberCollection = _old.GetType().GetMembers();

                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        Object fieldValue = field.GetValue(_old);
                        if (fieldValue == null)
                        {
                            continue;
                        }
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(_new, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            if ((fieldValue.GetType().IsValueType == true))
                            {
                                field.SetValue(_new, fieldValue);
                            }
                        }
                    }
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;
                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            object propertyValue = myProperty.GetValue(_old, null);
                            if (propertyValue == null)
                            {
                                continue;
                            }
                            if (propertyValue is ICloneable)
                            {
                                myProperty.SetValue(_new, (propertyValue as ICloneable).Clone(), null);
                            }
                            else
                            {
                                if ((propertyValue.GetType().IsValueType == true))
                                {
                                    myProperty.SetValue(_new, propertyValue);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
Esempio n. 37
0
        /// <summary>
        /// 深复制对象
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private object Copy(object obj)
        {
            //返回新的对象
            Object targetDeepCopyObj;
            Type   targetType = obj.GetType();

            if (targetType.IsValueType)
            {
                //值类型
                targetDeepCopyObj = obj;
            }
            else
            {
                //引用类型
                //创建一个实例
                targetDeepCopyObj = System.Activator.CreateInstance(targetType);
                //获取该实例的所有成员
                System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();
                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    //成员类型为字段时
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        Object fieldValue = field.GetValue(obj);
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, Copy(fieldValue));
                        }
                    }
                    //成员类型为属性时
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;
                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            object propertyValue = myProperty.GetValue(obj, null);
                            if (propertyValue is ICloneable)
                            {
                                myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                            }
                            else
                            {
                                myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);
                            }
                        }
                    }
                }
            }
            return(targetDeepCopyObj);
        }
Esempio n. 38
0
        public static void GuardarObjeto(Control[] unaListaControles, object unObjeto)
        {
            Control unControl = null;
            object  valor = null; bool establecer = true;

            for (int i = 0; i < unaListaControles.Count(); i++)
            {
                Application.DoEvents();
                establecer = true;
                unControl  = unaListaControles[i];

                Type tipo = unControl.GetType();
                if (tipo.Name == "TextBoxX" || tipo.Name == "PictureBox" || tipo.Name == "ComboBoxEx" || tipo.Name == "DateTimeInput" || tipo.Name == "CheckBox")
                {
                    object nombre = ExtraeNombre(unControl);

                    System.Reflection.PropertyInfo item = unObjeto.GetType().GetProperty(nombre.ToString());
                    if (item != null)
                    {
                        switch (tipo.Name)
                        {
                        case "TextBoxX":
                            if (!unControl.Name.EndsWith("RO"))
                            {
                                valor = unControl.Text;
                            }
                            else
                            {
                                establecer = false;
                            }
                            break;

                        case "PictureBox":
                            valor = ((PictureBox)unControl).Image;
                            break;

                        case "ComboBoxEx":
                            valor = ((ComboBox)unControl).SelectedValue;
                            break;

                        case "DateTimeInput":
                            valor = ((DevComponents.Editors.DateTimeAdv.DateTimeInput)unControl).Value;
                            break;

                        case "CheckBox":
                            valor = ((CheckBox)unControl).Checked;
                            break;
                        }
                        if (item.GetSetMethod() != null && establecer)
                        {
                            item.SetValue(unObjeto, valor, null);
                        }
                    }
                }
            }
        }
Esempio n. 39
0
        public static void ModPatch_RebindData(GlobalBindingModule __instance)
        {
            Console.WriteLine("Redirect DataManager to ModDataManager");
            // 重定向... 暂时在这里拿到Kernal 很方便
            System.Reflection.PropertyInfo propInfo = typeof(Game).GetProperty("Data");
            MethodInfo mi = propInfo.GetSetMethod(true);

            mi.Invoke(null, new object[] { new ModDataManager() });
            //__instance.Rebind<IDataProvider>().To<ModDataManager>().InSingletonScope();
        }
Esempio n. 40
0
 static public void SetPropertyValue(
     object obj, string propName, object value, object[] index
     )
 {
     System.Type type = obj.GetType();
     System.Reflection.PropertyInfo pi = type.GetProperty(propName);
     if (pi == null || pi.GetSetMethod(true) == null)
     {
         Debug.LogError("invalid state : " + propName);
         return;
     }
     pi.SetValue(obj, value, index);
 }
Esempio n. 41
0
        public static System.Action <TTarget, TValue> CreateSetter <TTarget, TValue>(System.Reflection.PropertyInfo propertyInfo, bool nonPublic)
        {
            if (propertyInfo == null)
            {
                throw new System.ArgumentNullException(nameof(propertyInfo));
            }

            if (typeof(TTarget).GetTypeInfo().IsValueType)
            {
                //throw new System.ArgumentException("The type of the isntance should not be a value type. " + "For a value type, use System.Object instead.", "propertyInfo");
                return(null);
            }

            if (propertyInfo.GetIndexParameters().Length > 0)
            {
                //throw new System.ArgumentException("Cannot create a dynamic setter for an indexed property.", "propertyInfo");
                return(null);
            }

            if (typeof(TTarget) != typeof(object) &&
                !propertyInfo.DeclaringType.IsAssignableFrom(typeof(TTarget)))
            {
                //throw new System.ArgumentException("The declaring type of the property is not assignable from the type of the isntance.", "propertyInfo");
                return(null);
            }

            if (typeof(TValue) != typeof(object) &&
                !propertyInfo.PropertyType.IsAssignableFrom(typeof(TValue)))
            {
                //throw new System.ArgumentException("The type of the property is not assignable from the type of the value.", "propertyInfo");
                return(null);
            }

            var setMethod = propertyInfo.GetSetMethod(nonPublic);

            if (setMethod == null)
            {
                //if (nonPublic)
                //{
                //    throw new System.ArgumentException("The property does not have a set method.", "propertyInfo");
                //}

                //throw new System.ArgumentException("The property does not have a public set method.", "propertyInfo");
                return(null);
            }

            return(EmitPropertySetter <TTarget, TValue>(propertyInfo, setMethod));
        }
Esempio n. 42
0
        internal void SetObjectProperty(Type t, object o, string propName, IValueFactory factory, IValueInitInfo valueInfo)
        {
            if (ReflectionCacheEnabled)
            {
                ReflectionPropertyCacheKey   cacheKey = new ReflectionPropertyCacheKey(t, propName);
                ReflectionPropertyCacheValue cacheValue;
                if (!propertyInfoCache.TryGetValue(cacheKey, out cacheValue))
                {
                    System.Reflection.PropertyInfo propInfo = t.GetProperty(propName);
                    if (propInfo == null)
                    {
                        throw new MissingMethodException(t.ToString(), propName);
                    }
                    MethodInfo setMethodInfo = propInfo.GetSetMethod(false);

                    DynamicMethod setDynMethod = new DynamicMethod(String.Empty, typeof(void), new Type[] { typeof(object), typeof(object) }, t, true);
                    ILGenerator   setGenerator = setDynMethod.GetILGenerator();
                    setGenerator.Emit(OpCodes.Ldarg_0);
                    setGenerator.Emit(OpCodes.Ldarg_1);
                    if (setMethodInfo.GetParameters()[0].ParameterType.IsValueType)
                    {
                        setGenerator.Emit(OpCodes.Unbox_Any, setMethodInfo.GetParameters()[0].ParameterType);
                    }
                    setGenerator.Emit(OpCodes.Call, setMethodInfo);
                    setGenerator.Emit(OpCodes.Ret);

                    cacheValue = new ReflectionPropertyCacheValue(
                        (PropertySetHandler)setDynMethod.CreateDelegate(typeof(PropertySetHandler)),
                        propInfo.PropertyType);
                    // despite the fact Dictionary is thread safe, for some reason sometimes exceptions are thrown without extra lock
                    lock (propertyInfoCache) {
                        propertyInfoCache[cacheKey] = cacheValue;
                    }
                }
                object value = valueInfo.GetValue(factory, cacheValue.PropertyType);
                cacheValue.SetHandler(o, value);
            }
            else
            {
                System.Reflection.PropertyInfo propInfo = t.GetProperty(propName);
                if (propInfo == null)
                {
                    throw new MissingMethodException(t.ToString(), propName);
                }
                propInfo.SetValue(o, valueInfo.GetValue(factory, propInfo.PropertyType), null);
            }
        }
Esempio n. 43
0
        /// <summary>
        /// 快速设置属性
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="pi">属性</param>
        /// <param name="obj">值</param>
        /// <param name="indexs">索引</param>
        public static void FastSetPropertyValue(object sender, System.Reflection.PropertyInfo pi, object obj, object[] indexs)
        {
            if (obj == null || obj.ToString() == "")
            {
                return;
            }

            //获取属性的赋值方法
            var setMethod = pi.GetSetMethod();
            var invoke    = FastInvoke.GetMethodInvoker(setMethod);

            if (pi.PropertyType != typeof(String))
            {
                if (obj != DBNull.Value || obj.ToString() != "")
                {
                    if (pi.PropertyType == typeof(Enum) || pi.PropertyType.BaseType == typeof(Enum))
                    {
                        invoke(sender, new object[] { Convert.ChangeType(obj, typeof(int), null), indexs });
                    }
                    else if (pi.PropertyType == typeof(Boolean) || pi.PropertyType.BaseType == typeof(Boolean))
                    {
                        var strv = obj.ToString();
                        var v    = 0;
                        var bv   = false;
                        if (int.TryParse(strv, out v))
                        {
                            bv = v != 0;
                        }
                        else
                        {
                            bv = "true".Equals(strv.Trim(), StringComparison.OrdinalIgnoreCase);
                        }
                        invoke(sender, new object[] { bv, indexs });
                    }
                    else
                    {
                        invoke(sender, new object[] { Convert.ChangeType(obj, pi.PropertyType, null), indexs });
                    }
                }
            }
            else
            {
                invoke(sender, new object[] { obj == DBNull.Value ? "" : obj.ToString(), indexs });
            }
        }
Esempio n. 44
0
        public void StoreComponent(IComponent[] comArray)
        {
            ComponentInfo = new IComponent[comArray.Length];
            int index = 0;

            foreach (var singleCom in comArray)
            {
                System.Type t   = singleCom.GetType();
                var         obj = System.Activator.CreateInstance(t);

                System.Reflection.MemberInfo[] memberCollection = singleCom.GetType().GetMembers();

                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;

                        System.Object fieldValue = field.GetValue(singleCom);

                        field.SetValue(obj, fieldValue);
                    }
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;

                        System.Reflection.MethodInfo info = myProperty.GetSetMethod(false);

                        if (info != null)
                        {
                            try
                            {
                                object propertyValue = myProperty.GetValue(singleCom, null);
                                myProperty.SetValue(obj, propertyValue, null);
                            }
                            catch (System.Exception ex)
                            {
                            }
                        }
                    }
                }

                ComponentInfo[index++] = obj as IComponent;
            }
        }
        static StackObject *GetSetMethod_11(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Reflection.PropertyInfo instance_of_this_method = (System.Reflection.PropertyInfo) typeof(System.Reflection.PropertyInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetSetMethod();

            object obj_result_of_this_method = result_of_this_method;

            if (obj_result_of_this_method is CrossBindingAdaptorType)
            {
                return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance));
            }
            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Esempio n. 46
0
        /// <summary>
        /// 配置属性的值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="pi"></param>
        /// <param name="obj"></param>
        public static void SetPropertyValue(object sender, System.Reflection.PropertyInfo pi, object obj, object[] indexs)
        {
            if (pi.CanWrite == false || obj == null || obj.ToString() == "")
            {
                return;
            }
            var setmethod = pi.GetSetMethod();

            if (setmethod == null || setmethod.IsPublic == false)
            {
                return;
            }

            if (pi.PropertyType != typeof(String))
            {
                if (pi.PropertyType == typeof(Enum) || pi.PropertyType.BaseType == typeof(Enum))
                {
                    pi.SetValue(sender, obj, indexs);//Convert.ChangeType(obj, typeof(int))
                }
                else if (pi.PropertyType == typeof(Boolean) || pi.PropertyType.BaseType == typeof(Boolean))
                {
                    pi.SetValue(sender, obj.Equals("true") || obj.Equals("1"), indexs);
                }
                else
                {
                    //if (!pi.PropertyType.FullName.Contains("System.")) //这里对自定义不做处理
                    //{
                    //    return;
                    //}

                    pi.SetValue(sender, Convert.ChangeType(obj, pi.PropertyType, null), indexs);
                }
            }
            else
            {
                pi.SetValue(sender, obj == DBNull.Value ? "" : obj.ToString(),
                            indexs);
            }
        }
Esempio n. 47
0
            Property LoadProperty(System.Reflection.PropertyInfo refProperty)
            {
                bool isStatic =
                    (refProperty.CanRead && refProperty.GetGetMethod().IsStatic) ||
                    (refProperty.CanRead && refProperty.GetGetMethod().IsStatic);

                System.Reflection.MethodInfo getMethod =
                    (refProperty.CanRead ? refProperty.GetGetMethod(false) : null);
                System.Reflection.MethodInfo setMethod =
                    (refProperty.CanWrite ? refProperty.GetSetMethod(false) : null);
                Property property = new Property
                {
                    Name         = refProperty.Name,
                    IsStatic     = isStatic,
                    PropertyType = GetTypeFullName(refProperty.PropertyType),
                    GetMethod    = (getMethod != null ? LoadMethod(getMethod) : null),
                    SetMethod    = (setMethod != null ? LoadMethod(setMethod) : null),
                    Attributes   = refProperty.Attributes,
                };

                property.IndexParameters = refProperty.GetIndexParameters().Select(p => LoadParameter(p)).ToList();
                return(property);
            }
        /// <summary>
        /// A property is serializable if:
        /// - it's not marked with any of the 'DontSerializeMember' attributes
        /// - it's an auto-property
        /// - has a public getter or setter, otherwise must be annotated with any of the 'SerializeMember' attributes
        /// - its type is serializable
        /// - static properties that meet the previous requirements are always serialized in Better[Behaviour|ScriptableObject],
        ///   and in System.Objects if the serializer of use supports it (FullSerialier doesn't)
        /// </summary>
        public override bool IsSerializableProperty(System.Reflection.PropertyInfo property)
        {
            foreach (System.Type v_type in DontSerializeMember)
            {
                if (property.IsDefined(v_type, false))
                {
                    return(false);
                }
            }

            if (!property.IsAutoProperty())
            {
                return(false);
            }

            bool v_isSerializableDefined = false;

            foreach (System.Type v_type in SerializeMember)
            {
                if (property.IsDefined(v_type, false))
                {
                    v_isSerializableDefined = true;
                    break;
                }
            }

            if (!(property.GetGetMethod(true).IsPublic ||
                  property.GetSetMethod(true).IsPublic ||
                  v_isSerializableDefined))
            {
                return(false);
            }

            bool serializable = IsSerializableType(property.PropertyType);

            return(serializable);
        }
    object DeepCopy(object obj)
    {
        System.Object targetDeepCopyObj = null;

        if (obj == null)
        {
            return(obj);
        }


        Type targetType = obj.GetType();

        //值类型
        if (targetType.IsValueType == true)
        {
            targetDeepCopyObj = obj;
        }
        //引用类型
        else
        {
            if (obj is UnityEngine.Object)
            {
                targetDeepCopyObj = UnityEngine.Object.Instantiate(obj as UnityEngine.Object);
            }
            else
            {
                targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //创建引用对象
            }
            System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();
            foreach (System.Reflection.MemberInfo member in memberCollection)
            {
                if (member.MemberType == System.Reflection.MemberTypes.Field)
                {
                    System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                    System.Object fieldValue          = field.GetValue(obj);
                    if (fieldValue is ICloneable)
                    {
                        field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                    }
                    else
                    {
                        field.SetValue(targetDeepCopyObj, DeepCopy(fieldValue));
                    }
                }
                else if (member.MemberType == System.Reflection.MemberTypes.Property)
                {
                    System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;
                    MethodInfo info = myProperty.GetSetMethod(false);
                    if (info != null)
                    {
                        object propertyValue = myProperty.GetValue(obj, null);
                        if (propertyValue is BaseObject)
                        {
                            continue;
                        }
                        if (propertyValue is ICloneable)
                        {
                            myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                        }
                        else
                        {
                            myProperty.SetValue(targetDeepCopyObj, DeepCopy(propertyValue), null);
                        }
                    }
                }
            }
        }
        return(targetDeepCopyObj);
    }
Esempio n. 50
0
 public static bool IsPublic(this PropertyInfo propertyInfo)
 {
     return((propertyInfo?.GetGetMethod(true)?.IsPublic ?? false) ||
            (propertyInfo?.GetSetMethod(true)?.IsPublic ?? false));
 }
Esempio n. 51
0
        //public static readonly System.Reflection.MethodInfo NameValueCollectionOpImplicitMethodInfo = typeof(NameValueCollection).GetMethod("op_Implicit",new Type[] { typeof(StringContainer)});
        /// <summary>
        /// 把parameters中的值转换为Model属性中相应类型的值
        /// </summary>
        /// <param name="methodIL"></param>
        /// <param name="model"></param>
        /// <param name="propertyInfo"></param>
        /// <param name="parametersGetItem"></param>
        public static void ConvertPropertyString(ILGenerator methodIL, System.Reflection.Emit.LocalBuilder model,
                                                 System.Reflection.PropertyInfo propertyInfo, System.Reflection.MethodInfo parametersGetItem)
        {
            Type propertyType = propertyInfo.PropertyType;
            bool isNullable   = false;

            if (propertyInfo.PropertyType
#if (NET40 || NET451 || NET461)
                .IsGenericType
#endif
#if NETCORE
                .GetTypeInfo().IsGenericType
#endif
                && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                isNullable   = true;
                propertyType = propertyInfo.PropertyType.GetGenericArguments()[0];
            }
            if (propertyType == typeof(System.String))
            {
                if (!propertyInfo.GetSetMethod().IsStatic)
                {
                    methodIL.Emit(OpCodes.Ldloc, model);                               //model
                    methodIL.Emit(OpCodes.Ldarg_0);                                    //model,nvc
                    methodIL.Emit(OpCodes.Ldstr, propertyInfo.Name);                   //model,nvc,key
                    methodIL.Emit(OpCodes.Callvirt, NameValueCollectionGetMethodInfo); //model,string
                    methodIL.Emit(OpCodes.Call, StringContainerOpImplicitMethodInfoDic[typeof(String).TypeHandle]);
                    methodIL.Emit(OpCodes.Call, propertyInfo.GetSetMethod());
                }
                else
                {
                    methodIL.Emit(OpCodes.Ldarg_0);                                    //nvc
                    methodIL.Emit(OpCodes.Ldstr, propertyInfo.Name);                   //nvc,key
                    methodIL.Emit(OpCodes.Callvirt, NameValueCollectionGetMethodInfo); //model,string
                    methodIL.Emit(OpCodes.Call, StringContainerOpImplicitMethodInfoDic[typeof(String).TypeHandle]);
                    methodIL.Emit(OpCodes.Call, propertyInfo.GetSetMethod());
                }
            }
            else if (propertyType == typeof(System.Int32) ||
                     propertyType == typeof(System.Int16) ||
                     propertyType == typeof(System.Int64) ||
                     propertyType == typeof(System.UInt32) ||
                     propertyType == typeof(System.UInt16) ||
                     propertyType == typeof(System.UInt64) ||
                     propertyType == typeof(System.Byte) ||
                     propertyType == typeof(System.SByte) ||
                     propertyType == typeof(System.Single) ||
                     propertyType == typeof(System.Double) ||
                     propertyType == typeof(System.Decimal) ||
                     propertyType == typeof(System.DateTime) ||
                     propertyType == typeof(System.DateTimeOffset) ||
                     propertyType == typeof(System.Char) ||
                     propertyType == typeof(System.Boolean) ||
                     propertyType == typeof(System.Guid)
                     )
            {
                if (!propertyInfo.GetSetMethod().IsStatic)
                {
                    methodIL.Emit(OpCodes.Ldloc, model);
                    methodIL.Emit(OpCodes.Ldarg_0);                                    //nvc
                    methodIL.Emit(OpCodes.Ldstr, propertyInfo.Name);                   //nvc,key
                    methodIL.Emit(OpCodes.Callvirt, NameValueCollectionGetMethodInfo); //model,string
                    methodIL.Emit(OpCodes.Call, StringContainerOpImplicitMethodInfoDic[propertyInfo.PropertyType.TypeHandle]);
                    methodIL.Emit(OpCodes.Callvirt, propertyInfo.GetSetMethod());
                }
                else
                {
                    methodIL.Emit(OpCodes.Ldarg_0);                                    //nvc
                    methodIL.Emit(OpCodes.Ldstr, propertyInfo.Name);                   //nvc,key
                    methodIL.Emit(OpCodes.Callvirt, NameValueCollectionGetMethodInfo); //model,string
                    methodIL.Emit(OpCodes.Call, StringContainerOpImplicitMethodInfoDic[propertyInfo.PropertyType.TypeHandle]);
                    methodIL.Emit(OpCodes.Call, propertyInfo.GetSetMethod());
                }
                if (isNullable)
                {
                    //var temp = methodIL.DeclareLocal(propertyType);
                    //var temp1 = methodIL.DeclareLocal(propertyInfo.PropertyType);
                    //var success = methodIL.DeclareLocal(typeof(Boolean));
                    //var elseCase = methodIL.DefineLabel();
                    //var endCase = methodIL.DefineLabel();
                    //methodIL.Emit(OpCodes.Ldarg_1);//nvc
                    //methodIL.Emit(OpCodes.Ldstr, propertyInfo.Name);//nvc,key
                    //methodIL.Emit(OpCodes.Callvirt, parametersGetItem);//string
                    ////string,temp
                    //methodIL.Emit(OpCodes.Ldloca_S,temp);
                    ////bool
                    //methodIL.Emit(OpCodes.Call, propertyType.GetMethod("TryParse", new Type[] { typeof(string), propertyType.MakeByRefType() }));
                    //methodIL.Emit(OpCodes.Stloc_S,success);
                    //methodIL.Emit(OpCodes.Ldloc_S,success);
                    ////
                    //methodIL.Emit(OpCodes.Brfalse_S,elseCase);
                    ////model
                    //methodIL.Emit(OpCodes.Ldarg_0);
                    ////model,temp
                    //methodIL.Emit(OpCodes.Ldloc,temp);
                    ////model.property=new Type();
                    //methodIL.Emit(OpCodes.Newobj,propertyInfo.PropertyType.GetConstructor(new Type[] { propertyType}));
                    ////model.property.setMethod(temp);
                    //methodIL.Emit(OpCodes.Callvirt,propertyInfo.GetSetMethod());
                    //methodIL.Emit(OpCodes.Br_S,endCase);

                    //methodIL.MarkLabel(elseCase);

                    //methodIL.Emit(OpCodes.Ldarg_0);
                    //methodIL.Emit(OpCodes.Ldloca_S,temp1);
                    //methodIL.Emit(OpCodes.Initobj,propertyInfo.PropertyType);
                    //methodIL.Emit(OpCodes.Ldloc_S,temp1);
                    //methodIL.Emit(OpCodes.Callvirt,propertyInfo.GetSetMethod());
                    //methodIL.MarkLabel(endCase);
                }
                else
                {
                    //methodIL.Emit(OpCodes.Ldarg_1);//nvc
                    //methodIL.Emit(OpCodes.Ldstr, propertyInfo.Name);//nvc,key
                    //methodIL.Emit(OpCodes.Callvirt, parametersGetItem);//string
                    //var temp = methodIL.DeclareLocal(propertyInfo.PropertyType);


                    ////methodIL.Emit(OpCodes.Ldc_I4_0);
                    ////methodIL.Emit(OpCodes.Stloc,temp);

                    ////string,&temp
                    //methodIL.Emit(OpCodes.Ldloca_S, temp);
                    ////bool
                    //methodIL.Emit(OpCodes.Call, propertyInfo.PropertyType.GetMethod("TryParse", new Type[] { typeof(string), propertyInfo.PropertyType.MakeByRefType() }));
                    ////
                    //methodIL.Emit(OpCodes.Pop);
                    //if (!propertyInfo.GetSetMethod().IsStatic)
                    //{
                    //    //model
                    //    methodIL.Emit(OpCodes.Ldarg_0);
                    //}
                    ////model,temp
                    //methodIL.Emit(OpCodes.Ldloc, temp);
                    ////model.property=temp
                    //methodIL.Emit(OpCodes.Call, propertyInfo.GetSetMethod());
                }
            }
        }
Esempio n. 52
0
        /// <summary>
        /// 复制对象到剪贴板
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="mode">复制模式:0:表格模式(制表符分隔) , 1:文本模式(换行分隔)</param>
        /// <returns></returns>
        public static string ClipString(this object obj, int mode = 0)
        {
            var  items      = new List <string>();
            Type targetType = obj.GetType();

                        //值类型
                        if(targetType.IsValueType == true)
            {
                return(obj.ToString());
            }

                        //引用类型
                        else
            {
                //targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //创建引用对象
                                System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();

                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        Object fieldValue = field.GetValue(obj);
                        if (fieldValue is ICloneable)
                        {
                            items.Add((fieldValue as ICloneable).ToString());
                            //field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            items.Add(fieldValue.ToString());
                            //field.SetValue(targetDeepCopyObj, Copy(fieldValue));
                        }
                    }
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;
                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            object propertyValue = myProperty.GetValue(obj, null);
                            if (propertyValue is ICloneable)
                            {
                                items.Add((propertyValue as ICloneable).ToString());
                                //myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                            }
                            else
                            {
                                if (propertyValue != null)
                                {
                                    items.Add(propertyValue.ToString());
                                    //myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);
                                }
                                else
                                {
                                    items.Add("");
                                }
                            }
                        }
                    }
                }

                return(string.Join("\t", items));
            }
        }
    // 反射实现深拷贝
    public static object DeepCopyByReflection(object obj)
    {
        if (obj == null)
        {
            return(null);
        }

        System.Object targetObj;
        Type          targetType = obj.GetType();

        // 对于值类型,直接使用=即可
        if (targetType.IsValueType == true)
        {
            targetObj = obj;
        }
        else
        {
            // 对于引用类型
            // 根据targetType创建引用对象
            targetObj = System.Activator.CreateInstance(targetType);
            // 使用反射获取targetType下所有的成员
            System.Reflection.MemberInfo[] memberInfos = obj.GetType().GetMembers();

            // 遍历所有的成员
            foreach (System.Reflection.MemberInfo member in memberInfos)
            {
                // 如果成员为字段类型:获取obj中该字段的值。
                if (member.MemberType == System.Reflection.MemberTypes.Field)
                {
                    System.Reflection.FieldInfo fieldInfo = (System.Reflection.FieldInfo)member;
                    System.Object fieldValue = fieldInfo.GetValue(obj);

                    //如果该值可直接Clone,则直接Clone;否则,递归调用DeepCopyByReflection(该值)。
                    if (fieldValue is ICloneable)
                    {
                        fieldInfo.SetValue(targetObj, (fieldValue as ICloneable).Clone());
                    }
                    else
                    {
                        fieldInfo.SetValue(targetObj, DeepCopyByReflection(fieldValue));
                    }
                }
                // 如果成员为属性类型:获取obj中该属性的值。
                else if (member.MemberType == System.Reflection.MemberTypes.Property)
                {
                    System.Reflection.PropertyInfo propertyInfo = (System.Reflection.PropertyInfo)member;

                    // GetSetMethod(nonPublic) nonPublic means: sIndicates whether the accessor should be returned if it is non-public. true if a non-public accessor is to be returned; otherwise, false.
                    System.Reflection.MethodInfo methodInfo = propertyInfo.GetSetMethod(false);

                    if (methodInfo != null)
                    {
                        try {
                            // 如果该值可直接CLone,则直接Clone;否则,递归调用DeepCopyByReflection(该值)。
                            object propertyValue = propertyInfo.GetValue(obj, null);
                            if (propertyValue is ICloneable)
                            {
                                propertyInfo.SetValue(targetObj, (propertyValue as ICloneable).Clone(), null);
                            }
                            else
                            {
                                propertyInfo.SetValue(targetObj, DeepCopyByReflection(propertyValue), null);
                            }
                        } catch (Exception e) {
                            // some thing except.
                            Debug.Log(e.Message);
                        }
                    }
                }
            }
        }

        return(targetObj);
    }
Esempio n. 54
0
        public GameObject Instantiate(Transform parent)
        {
            GameObject go = new GameObject(name);

            go.transform.parent           = parent;
            go.transform.localPosition    = positon;
            go.transform.localEulerAngles = rotation;
            go.transform.localScale       = scale;

            guids.Add(guid, go);

            if (children != null)
            {
                foreach (JGameObject jgo in children)
                {
                    jgo.Instantiate(go.transform);
                }
            }

            foreach (JComponent jc in components)
            {
                Type type = Type.GetType(jc.type);
                if (type != null)
                {
                    if (go.GetComponent(type) != null)
                    {
                        guids.Add(jc.guid, go.GetComponent(type));
                    }
                    else
                    {
                        Component c = go.AddComponent(type);
                        guids.Add(jc.guid, c);

                        foreach (JField field in jc.fields)
                        {
                            try
                            {
                                if (field.value is string && ((string)field.value).StartsWith("{{ ") && ((string)field.value).EndsWith(" }}"))
                                {
                                    SetObjectValue((string)field.value, (UnityEngine.Object obj) => type.GetField(field.name).SetValue(c, obj));
                                }
                                else
                                {
                                    type.GetField(field.name).SetValue(c, field.value);
                                }
                            } catch (Exception e)
                            {
                                Debug.Log("Failed to set field " + type.Name + "." + field.name + " to " + field.value);
                            }
                        }
                        foreach (JProperty prop in jc.properties)
                        {
                            try
                            {
                                System.Reflection.PropertyInfo pi = type.GetProperty(prop.name);
                                if (pi.GetSetMethod() == null)
                                {
                                    continue;
                                }

                                if (prop.value is string && ((string)prop.value).StartsWith("{{ ") && ((string)prop.value).EndsWith(" }}"))
                                {
                                    SetObjectValue((string)prop.value, (UnityEngine.Object obj) => pi.SetValue(c, Convert.ChangeType(obj, pi.PropertyType), null));
                                }
                                else
                                {
                                    pi.SetValue(c, Convert.ChangeType(prop.value, pi.PropertyType), null);
                                }
                            }
                            catch (Exception e)
                            {
                                Debug.Log("Failed to set prop " + type.Name + "." + prop.name + " to " + prop.value);
                            }
                        }
                    }
                }
                else
                {
                    Debug.Log("Skipping type " + jc.type + "!");
                }
            }

            return(go);
        }
Esempio n. 55
0
        private static object CopyOjbect(object obj)
        {
            if (obj == null)
            {
                return(null);
            }

            //拷贝目标
            Object targetDeepCopyObj;

            //元类型
            Type targetType = obj.GetType();

            //值类型
            if (targetType.IsValueType == true)
            {
                targetDeepCopyObj = obj;
            }
            //引用类型
            else
            {
                //创建引用对象
                targetDeepCopyObj = System.Activator.CreateInstance(targetType);

                //获取引用对象的所有公共成员
                System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();

                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    //拷贝字段
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        Object fieldValue = field.GetValue(obj);
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, CopyOjbect(fieldValue));
                        }
                    }//拷贝属性
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;

                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            try
                            {
                                object propertyValue = myProperty.GetValue(obj, null);
                                if (propertyValue is ICloneable)
                                {
                                    myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                                }
                                else
                                {
                                    myProperty.SetValue(targetDeepCopyObj, CopyOjbect(propertyValue), null);
                                }
                            }
                            catch
                            {
                                //TODO
                                //输出你要处理的异常代码
                            }
                        }
                    }
                }
            }
            return(targetDeepCopyObj);
        }
Esempio n. 56
0
        /// <summary>
        /// 对象拷贝-无效
        /// </summary>
        /// <param name="t">被复制对象</param>
        /// <returns>新对象</returns>
        public static T CopyOjbect <T>(this T t) where T : class
        {
            if (t == null)
            {
                return(null);
            }
            T    model;
            Type targetType = t.GetType();

            if (targetType.IsValueType == true)//值类型
            {
                model = t;
            }
            else//引用类型
            {
                model = System.Activator.CreateInstance <T>();   //创建引用对象
                System.Reflection.MemberInfo[] memberCollection = t.GetType().GetMembers();

                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    //拷贝字段
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        Object fieldValue = field.GetValue(t);
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(model, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(model, CopyOjbect(fieldValue));
                        }
                    }//拷贝属性
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;

                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            try
                            {
                                object propertyValue = myProperty.GetValue(t, null);
                                if (propertyValue is ICloneable)
                                {
                                    myProperty.SetValue(model, (propertyValue as ICloneable).Clone(), null);
                                }
                                else
                                {
                                    myProperty.SetValue(model, CopyOjbect(propertyValue), null);
                                }
                            }
                            catch (System.Exception ex)
                            {
                            }
                        }
                    }
                }
            }
            return(model);
        }
        /// <summary>
        /// 深拷贝
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        static object DeepCopy(object obj)
        {
            if (obj == null)
            {
                return(null);
            }

            object targetDeepCopyObj;
            Type   targetType = obj.GetType();

            //值类型
            if (targetType.IsValueType == true)
            {
                targetDeepCopyObj = obj;
            }
            //引用类型
            else
            {
                //创建引用对象
                if (obj is ScriptableObject)
                {
                    targetDeepCopyObj = SelectTree.CreateNode(targetType);
                }
                else
                {
                    targetDeepCopyObj = System.Activator.CreateInstance(targetType);
                }

                // 拷贝成员变量
                System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();
                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    //拷贝字段
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        object fieldValue = field.GetValue(obj);
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, DeepCopy(fieldValue));
                        }
                    }
                    //拷贝属性
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;

                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            try
                            {
                                object propertyValue = myProperty.GetValue(obj, null);
                                if (propertyValue is ICloneable)
                                {
                                    myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                                }
                                else
                                {
                                    myProperty.SetValue(targetDeepCopyObj, DeepCopy(propertyValue), null);
                                }
                            }
                            catch (System.Exception ex)
                            {
                            }
                        }
                    }
                }
            }

            return(targetDeepCopyObj);
        }
Esempio n. 58
0
        /// <summary>
        /// 配置属性的值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="pi"></param>
        /// <param name="obj"></param>
        public static void SetPropertyValue(object sender, System.Reflection.PropertyInfo pi, object obj, object[] indexs)
        {
            if (pi.CanWrite == false || obj == null || obj.ToString() == "")
            {
                return;
            }
            var setmethod = pi.GetSetMethod();

            if (setmethod == null || setmethod.IsPublic == false)
            {
                return;
            }

            if (pi.PropertyType != typeof(String))
            {
                if (pi.PropertyType == typeof(Enum) || pi.PropertyType.BaseType == typeof(Enum))
                {
                    pi.SetValue(sender, obj, indexs);//Convert.ChangeType(obj, typeof(int))
                }
                else if (pi.PropertyType == typeof(Boolean) || pi.PropertyType.BaseType == typeof(Boolean))
                {
                    pi.SetValue(sender, "true".Equals(obj.ToString(), StringComparison.OrdinalIgnoreCase) || "1".Equals(obj.ToString()), indexs);
                }
                else
                {
                    try
                    {
                        if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
                        {
                            var t = pi.PropertyType.GetGenericArguments()[0];
                            obj = Convert.ChangeType(obj, t);
                        }
                        else
                        {
                            obj = Convert.ChangeType(obj, pi.PropertyType);
                        }

                        pi.SetValue(sender, obj, indexs);

                        pi.SetValue(sender,
                                    Convert.ChangeType(obj, pi.PropertyType),
                                    indexs);
                    }
                    catch (Exception ex)
                    {
                        DoNet.Common.IO.Logger.Write(ex.ToString());
                        DoNet.Common.IO.Logger.Write("convert obj[" + obj.ToString() + "] to " + pi.PropertyType.ToString());
                    }
                }
            }
            else
            {
                if (obj.GetType() == typeof(byte[]))
                {
                    var v = System.Text.Encoding.UTF8.GetString((byte[])obj);
                    pi.SetValue(sender, v, indexs);
                }
                else
                {
                    pi.SetValue(sender, obj == DBNull.Value ? "" : obj.ToString(),
                                indexs);
                }
            }
        }
Esempio n. 59
0
        /// <summary>
        /// 快速设置属性
        /// </summary>
        /// <param name="sender">对象</param>
        /// <param name="pi">属性</param>
        /// <param name="obj">值</param>
        /// <param name="indexs">索引</param>
        public static void FastSetPropertyValue(object sender, System.Reflection.PropertyInfo pi, object obj, object[] indexs)
        {
            if (pi.CanWrite == false)
            {
                return;
            }
            if (obj == null || obj == DBNull.Value || obj.ToString() == "")
            {
                if (pi.PropertyType == typeof(DateTime))
                {
                    obj = DateTime.Parse("1900-01-01 00:00:00");
                }
                else
                {
                    return;
                }
            }

            //获取属性的赋值方法
            var setMethod = pi.GetSetMethod();

            if (setMethod == null || setMethod.IsPublic == false)
            {
                return;
            }

            var invoke = FastInvoke.GetMethodInvoker(setMethod);

            if (invoke == null)
            {
                return;
            }

            if (pi.PropertyType != typeof(String))
            {
                if (obj != DBNull.Value || obj.ToString() != "")
                {
                    if (pi.PropertyType == typeof(Enum) || pi.PropertyType.BaseType == typeof(Enum))
                    {
                        invoke(sender, new object[] { Convert.ChangeType(obj, typeof(int)), indexs });
                    }
                    else if (pi.PropertyType == typeof(Boolean) || pi.PropertyType.BaseType == typeof(Boolean))
                    {
                        var strv = obj.ToString();
                        var v    = 0;
                        var bv   = false;
                        if (int.TryParse(strv, out v))
                        {
                            bv = v != 0;
                        }
                        else
                        {
                            bv = "true".Equals(strv.Trim(), StringComparison.OrdinalIgnoreCase);
                        }
                        invoke(sender, new object[] { bv, indexs });
                    }
                    else
                    {
                        try
                        {
                            if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
                            {
                                var t = pi.PropertyType.GetGenericArguments()[0];
                                obj = Convert.ChangeType(obj, t);
                            }
                            else
                            {
                                obj = Convert.ChangeType(obj, pi.PropertyType);
                            }

                            invoke(sender, new object[] { obj, indexs });
                        }
                        catch (Exception ex)
                        {
                            DoNet.Common.IO.Logger.Write(ex.ToString());
                            DoNet.Common.IO.Logger.Write("convert obj[" + obj.ToString() + "] to " + pi.PropertyType.ToString());
                        }
                    }
                }
            }
            else
            {
                invoke(sender, new object[] { obj == DBNull.Value ? "" : obj.ToString(), indexs });
            }
        }
        public GetSetGeneric(PropertyInfo info)
        {
            Name = info.Name;
            Info = info;
            CollectionType = Info.PropertyType.GetInterface ("IEnumerable", true) != null;
            var getMethod = info.GetGetMethod (true);
            var setMethod = info.GetSetMethod (true);
            if(getMethod == null)
            {

                Get = (o)=> {
                    return info.GetValue(o, null);
                };
                Set = (o,v) => {
                    info.SetValue(o, v, null);
                };
                return;
            }
            Get = (o) => {
                    return getMethod.Invoke (o, null);
            };
            Set = (o,v) => {
                try {
                    setMethod.Invoke (o, new [] {v});
                } catch (Exception e) {
                    Radical.LogWarning (string.Format("When setting {0} to {1} found {2}:", o.ToString(), v.ToString(), e.ToString ()));
                }
            };
        }