Ejemplo n.º 1
0
        void init(PropertyInfo property)
        {
            if (property == null)
            {
                throw new ArgumentException("Argument: property is null");
            }
            var getmethod = property.GetGetMethod();
            var setmethod = property.GetSetMethod();

            //PropertyGet = new DelegateMethodInvoker(property.GetGetMethod());
            //PropertySet = new DelegateMethodInvoker(property.GetSetMethod());

            var name = ReflectionHelper.GetMemberSignName(property);
            var type = property.DeclaringType;

            if (getmethod != null && !getmethod.IsPublic)
            {
                PropertyGet = obj => property.GetValue(obj, null);
            }
            else
            {
                DynamicMethod method = new DynamicMethod(name + "_get", ReflectionHelper.ObjectType, new Type[] { ReflectionHelper.ObjectType });
                var           il     = method.GetILGenerator();
                if (getmethod != null)
                {
                    ReflectionHelper.ILLdarg(il, 0);
                    ReflectionHelper.ILCastclass(il, ReflectionHelper.ObjectType, type);
                    il.Emit(OpCodes.Callvirt, getmethod);
                    ReflectionHelper.ILCastclass(il, property.PropertyType, ReflectionHelper.ObjectType);
                    il.Emit(OpCodes.Ret);
                }
                else
                {
                    ReflectionHelper.ILThrow <MethodAccessException>(il, "get method not found");
                }
                PropertyGet = (Func <object, object>)method.CreateDelegate(typeof(Func <object, object>));
            }
            if (setmethod != null && !setmethod.IsPublic)
            {
                PropertySet = (obj, val) => property.SetValue(obj, val, null);
            }
            else
            {
                DynamicMethod method = new DynamicMethod(name + "_set", ReflectionHelper.VoidType, new Type[] { ReflectionHelper.ObjectType, ReflectionHelper.ObjectType });
                var           il     = method.GetILGenerator();
                if (setmethod != null)
                {
                    ReflectionHelper.ILLdarg(il, 0);
                    ReflectionHelper.ILCastclass(il, ReflectionHelper.ObjectType, type);
                    ReflectionHelper.ILLdarg(il, 1);
                    ReflectionHelper.ILCastclass(il, ReflectionHelper.ObjectType, property.PropertyType);
                    il.Emit(OpCodes.Callvirt, setmethod);
                    il.Emit(OpCodes.Ret);
                }
                else
                {
                    ReflectionHelper.ILThrow <MethodAccessException>(il, "set method not found");
                }

                PropertySet = (Action <object, object>)method.CreateDelegate(typeof(Action <object, object>));
            }
        }