DefineProperty() public method

public DefineProperty ( string name, System attributes, System returnType, System parameterTypes ) : System.Reflection.Emit.PropertyBuilder
name string
attributes System
returnType System
parameterTypes System
return System.Reflection.Emit.PropertyBuilder
Example #1
0
 private static FieldBuilder CréeAttributs(TypeBuilder constructeurDeType, DataColumn colonne)
 {
     FieldBuilder champBldr = null;
     PropertyBuilder constructeurPropriété;
     #region Création de l'attribut
     champBldr = constructeurDeType.DefineField(colonne.ColumnName.ToLower(), colonne.DataType, FieldAttributes.Private);
     #endregion
     #region Création de la Propriété associée
     constructeurPropriété = constructeurDeType.DefineProperty(colonne.ColumnName, System.Reflection.PropertyAttributes.HasDefault, colonne.DataType, null);
     // Choix des attributs
     MethodAttributes attrGetSet = MethodAttributes.Public |
        MethodAttributes.SpecialName | MethodAttributes.HideBySig;
     #region Définition du "getter".
     MethodBuilder constructeurGet = constructeurDeType.DefineMethod("get_" + colonne.ColumnName, attrGetSet, colonne.DataType, Type.EmptyTypes);
     ILGenerator champGetIL = constructeurGet.GetILGenerator();
     champGetIL.Emit(OpCodes.Ldarg_0);
     champGetIL.Emit(OpCodes.Ldfld, champBldr);
     champGetIL.Emit(OpCodes.Ret);
     #endregion
     #region Définition du "setter".
     MethodBuilder constructeurSet = constructeurDeType.DefineMethod("set_" + colonne.ColumnName, attrGetSet, null, new Type[] { colonne.DataType });
     ILGenerator champSetIL = constructeurSet.GetILGenerator();
     champSetIL.Emit(OpCodes.Ldarg_0);
     champSetIL.Emit(OpCodes.Ldarg_1);
     champSetIL.Emit(OpCodes.Stfld, champBldr);
     champSetIL.Emit(OpCodes.Ret);
     #endregion
     #region Association des accesseurs à la propriété
     constructeurPropriété.SetGetMethod(constructeurGet);
     constructeurPropriété.SetSetMethod(constructeurSet);
     #endregion
     #endregion
     return champBldr;
     }
Example #2
0
        private static void CreateProperty(System.Reflection.Emit.TypeBuilder tb, string propertyName, Type propertyType)
        {
            FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);

            PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
            MethodBuilder   getPropMthdBldr = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
            ILGenerator     getIl           = getPropMthdBldr.GetILGenerator();

            getIl.Emit(OpCodes.Ldarg_0);
            getIl.Emit(OpCodes.Ldfld, fieldBuilder);
            getIl.Emit(OpCodes.Ret);

            MethodBuilder setPropMthdBldr =
                tb.DefineMethod("set_" + propertyName,
                                MethodAttributes.Public |
                                MethodAttributes.SpecialName |
                                MethodAttributes.HideBySig,
                                null, new[] { propertyType });

            ILGenerator setIl          = setPropMthdBldr.GetILGenerator();
            Label       modifyProperty = setIl.DefineLabel();
            Label       exitSet        = setIl.DefineLabel();

            setIl.MarkLabel(modifyProperty);
            setIl.Emit(OpCodes.Ldarg_0);
            setIl.Emit(OpCodes.Ldarg_1);
            setIl.Emit(OpCodes.Stfld, fieldBuilder);

            setIl.Emit(OpCodes.Nop);
            setIl.MarkLabel(exitSet);
            setIl.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
        private static void BuildStringProperty(TypeBuilder typeBuilder, string property)
        {
            //implement properties from interface
            FieldBuilder fieldBuilder = typeBuilder.DefineField(property.ToLower(), typeof(string), FieldAttributes.Private);
            PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(property, PropertyAttributes.HasDefault, typeof(string), null);
            const MethodAttributes getSetAttributes = MethodAttributes.Public | MethodAttributes.SpecialName |
                                                      MethodAttributes.HideBySig | MethodAttributes.Virtual;
            //define 'get' accessor
            MethodBuilder getPropertyBuilder = typeBuilder.DefineMethod("get_" + property, getSetAttributes, typeof(string),
                                                                        Type.EmptyTypes);
            //create IL code for get
            ILGenerator genusGetIL = getPropertyBuilder.GetILGenerator();
            genusGetIL.Emit(OpCodes.Ldarg_0);
            genusGetIL.Emit(OpCodes.Ldfld, fieldBuilder);
            genusGetIL.Emit(OpCodes.Ret);

            //define 'set' accessor
            MethodBuilder setPropertyBuilder = typeBuilder.DefineMethod("set_" + property, getSetAttributes, null,
                                                                        new[] { typeof(String) });
            //create IL code for set
            ILGenerator genusSetIL = setPropertyBuilder.GetILGenerator();
            genusSetIL.Emit(OpCodes.Ldarg_0);
            genusSetIL.Emit(OpCodes.Ldarg_1);
            genusSetIL.Emit(OpCodes.Stfld, fieldBuilder);
            genusSetIL.Emit(OpCodes.Ret);

            //map get and set to property 'methods'
            propertyBuilder.SetGetMethod(getPropertyBuilder);
            propertyBuilder.SetSetMethod(setPropertyBuilder);
        }
Example #4
0
        internal static void CreateReadOnlyLazyProperty(TypeBuilder tb, PropertyInfo property, ILGenerator ctor, bool isInterfaceImplementation = true)
        {
            var propertyName = property.Name;
            var propertyType = property.PropertyType;

            //backing field
            var lazyType = typeof(Lazy<>).MakeGenericType(propertyType);
            var fb = tb.DefineField("_backing_" + propertyName, lazyType, FieldAttributes.Private);

            //property
            var pb = tb.DefineProperty(propertyName, PropertyAttributes.None, propertyType, null);

            //getter
            var getterAttributes = isInterfaceImplementation ? InterfaceImplementationAttributes : OverrideAttributes;
            var getMethod = tb.DefineMethod("get_" + propertyName, getterAttributes, propertyType, Type.EmptyTypes);
            var getIL = getMethod.GetILGenerator();
            getIL.DeclareLocal(propertyType);
            getIL.Emit(OpCodes.Nop);
            getIL.Emit(OpCodes.Ldarg_0);
            getIL.Emit(OpCodes.Ldfld, fb);
            getIL.EmitCall(OpCodes.Callvirt, lazyType.GetProperty("Value").GetGetMethod(), null);
            getIL.Emit(OpCodes.Stloc_0);
            getIL.Emit(OpCodes.Nop); //originally a br.s to the next line
            getIL.Emit(OpCodes.Ldloc_0);
            getIL.Emit(OpCodes.Ret);

            //combine getter and property
            pb.SetGetMethod(getMethod);

            //initialize Lazy<T> in .ctor
            ctor.Emit(OpCodes.Ldarg_0);
            ctor.Emit(OpCodes.Newobj, lazyType.GetConstructor(Type.EmptyTypes));
            ctor.Emit(OpCodes.Stfld, fb);
        }
        /// <summary>
        ///   CreateProperty
        /// </summary>
        /// <param name="pi"></param>
        /// <param name="methods"></param>
        /// <param name="typeBuilder"></param>
        /// <param name="privateSetters"></param>
        private static FieldBuilder CreateProperty(this PropertyInfo pi, ICollection <MethodInfo> methods, System.Reflection.Emit.TypeBuilder typeBuilder, bool privateSetters)
        {
            // Create underlying field; all properties have a field of the same type
            var backingField = typeBuilder.DefineField($"<{pi.Name}>k_BackingField", pi.PropertyType, FieldAttributes.Private);

            // Attribute:
            // [CompilerGenerated]
            var compilerGeneratedAttr = typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes);

            if (compilerGeneratedAttr != null)
            {
                // ReSharper disable once InconsistentNaming
                var fieldCABuilder = new CustomAttributeBuilder(compilerGeneratedAttr, new object[] { });
                backingField.SetCustomAttribute(fieldCABuilder);
            }

            // The last argument of DefineProperty is null, because the
            // property has no parameters. (If you don't specify null, you must
            // specify an array of Type objects. For a parameterless property,
            // use an array with no elements: new Type[] {})
            var propBldr = typeBuilder.DefineProperty(pi.Name, PropertyAttributes.HasDefault, CallingConventions.HasThis, pi.PropertyType, Type.EmptyTypes);

            var container = new BuilderData {
                _typeBuilder = typeBuilder, _fieldBuilder = backingField, _propertyBuilder = propBldr
            };

            // Disregard exceptions so that the custom defined properties can be used with the same algorithms even though their backing methods have not yet been defined.
            MethodInfo getter = null, setter = null;

            try {
                getter = pi.GetGetMethod();
                setter = pi.GetSetMethod();
            } catch (Exception) {
                // ignored
            }

            var jmpTable = new Dictionary <Instr, KeyValuePair <MethodInfo, PropertyType> > {
                { Instr.Getter, new KeyValuePair <MethodInfo, PropertyType>(getter, GetProperty) }, { Instr.Setter, new KeyValuePair <MethodInfo, PropertyType>(setter, SetProperty) }
            };

            foreach (var z in jmpTable)
            {
                if (z.Key == Instr.Setter && privateSetters)
                {
                    container._methodAttributes = MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual;
                }

                // If there is a getter in the interface, create a getter in the new type
                if (pi.ReflectedType != null)
                {
                    if (z.Value.Key != null)
                    {
                        methods.Remove(z.Value.Key);
                    }
                }
                z.Value.Value(z.Value.Key, container);
            }

            return(backingField);
        }
Example #6
0
            private static void BuildProperty(TypeBuilder typeBuilder, string name, Type type)
            {
                FieldBuilder field = typeBuilder.DefineField("m" + name, type, FieldAttributes.Private);
                PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(name, PropertyAttributes.None, type, null);

                MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Virtual;

                MethodBuilder getter = typeBuilder.DefineMethod("get_" + name, getSetAttr, type, Type.EmptyTypes);

                ILGenerator getIL = getter.GetILGenerator();
                getIL.Emit(OpCodes.Ldarg_0);
                getIL.Emit(OpCodes.Ldfld, field);
                getIL.Emit(OpCodes.Ret);

                MethodBuilder setter = typeBuilder.DefineMethod("set_" + name, getSetAttr, null, new Type[] { type });

                ILGenerator setIL = setter.GetILGenerator();
                setIL.Emit(OpCodes.Ldarg_0);
                setIL.Emit(OpCodes.Ldarg_1);
                setIL.Emit(OpCodes.Stfld, field);
                setIL.Emit(OpCodes.Ret);


                propertyBuilder.SetGetMethod(getter);
                propertyBuilder.SetSetMethod(setter);
            }
Example #7
0
 /// <summary>
 /// 动态创建类的属性
 /// </summary>
 /// <param name="tb">承载该属性的类型</param>
 /// <param name="properityName">属性名,首字母应大写</param>
 /// <param name="properityType">属性数据类型</param>
 public static FieldBuilder createProperty(TypeBuilder tb, string propertyName, Type propertyType)
 {
     //定义属性对应的私有字段
     FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);
     //定义属性
     PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
     //定义与属性相关的get方法
     MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName,
         MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
         propertyType,
         Type.EmptyTypes);
     ILGenerator getIL = getPropMthdBldr.GetILGenerator();//获取il 生成器
     getIL.Emit(OpCodes.Ldarg_0);
     getIL.Emit(OpCodes.Ldfld, fieldBuilder);
     getIL.Emit(OpCodes.Ret);
     //定义与属性相关的set方法
     MethodBuilder setPropMthdBldr = tb.DefineMethod("set_" + propertyName,
         MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
         null, new Type[] { propertyType });
     ILGenerator setIL = setPropMthdBldr.GetILGenerator();
     /*
      * OpCodes.Ldarg_0:Ldarg是加载方法参数的意思。这里Ldarg_0事实上是对当前对象的引用即this。
      * 因为类的实例方法(非静态方法)在调用时,this 是会作为第一个参数传入的。
      */
     setIL.Emit(OpCodes.Ldarg_0);
     setIL.Emit(OpCodes.Ldarg_1);//OpCodes.Ldarg_1:加载参数列表的第一个参数了。
     setIL.Emit(OpCodes.Stfld, fieldBuilder);//OpCodes.Stfld:用新值替换在对象引用或指针的字段中存储的值。
     setIL.Emit(OpCodes.Ret);
     //把get/set方法和属性联系起来
     propertyBuilder.SetGetMethod(getPropMthdBldr);
     propertyBuilder.SetSetMethod(setPropMthdBldr);
     return fieldBuilder;
 }
        public override void Extend(Type baseType, TypeBuilder typeBuilder)
        {
            //build field
            FieldBuilder field = typeBuilder.DefineField(FieldName, Type, FieldAttributes.Private);

            //define property
            PropertyBuilder property = typeBuilder.DefineProperty(Name, PropertyAttributes.None, Type, null);

            //build setter
            MethodBuilder setter = typeBuilder.DefineMethod("set_" + Name, MethodAttributes.Public | MethodAttributes.Virtual, null, new Type[] { Type });
            ILGenerator setterILG = setter.GetILGenerator();
            setterILG.Emit(OpCodes.Ldarg_0);
            setterILG.Emit(OpCodes.Ldarg_1);
            setterILG.Emit(OpCodes.Stfld, field);
            setterILG.Emit(OpCodes.Ret);
            property.SetSetMethod(setter);

            //build getter
            MethodBuilder getter = typeBuilder.DefineMethod("get_" + Name, MethodAttributes.Public | MethodAttributes.Virtual, Type, Type.EmptyTypes);
            ILGenerator getterILG = getter.GetILGenerator();
            getterILG.Emit(OpCodes.Ldarg_0);
            getterILG.Emit(OpCodes.Ldfld, field);
            getterILG.Emit(OpCodes.Ret);
            property.SetGetMethod(getter);
        }
 internal static PropertyBuilder DefineProperty(TypeBuilder typeBuilder,
     string name, Type type)
 {
     return typeBuilder.DefineProperty(name,
                                       PropertyAttributes.HasDefault,
                                       type, null);
 }
        private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
        {
            FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName,
                                                        propertyType,
                                                        FieldAttributes.Private);

            PropertyBuilder propertyBuilder =
                tb.DefineProperty(
                    propertyName, System.Reflection.PropertyAttributes.HasDefault, propertyType, null);
            MethodBuilder getPropMthdBldr =
                tb.DefineMethod("get_" + propertyName,
                    MethodAttributes.Public |
                    MethodAttributes.SpecialName |
                    MethodAttributes.HideBySig,
                    propertyType, Type.EmptyTypes);
            ILGenerator getIL = getPropMthdBldr.GetILGenerator();
            getIL.Emit(OpCodes.Ldarg_0);
            getIL.Emit(OpCodes.Ldfld, fieldBuilder);
            getIL.Emit(OpCodes.Ret);
            MethodBuilder setPropMthdBldr =
                tb.DefineMethod("set_" + propertyName,
                  MethodAttributes.Public |
                  MethodAttributes.SpecialName |
                  MethodAttributes.HideBySig,
                  null, new Type[] { propertyType });
            ILGenerator setIL = setPropMthdBldr.GetILGenerator();
            setIL.Emit(OpCodes.Ldarg_0);
            setIL.Emit(OpCodes.Ldarg_1);
            setIL.Emit(OpCodes.Stfld, fieldBuilder);
            setIL.Emit(OpCodes.Ret);
            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
        private void CreateProperty(TypeBuilder a_TypeBuilder, string a_PropertyName, Type a_PropertyType)
        {
            FieldBuilder fieldBuilder = a_TypeBuilder.DefineField("_" + a_PropertyName, a_PropertyType, FieldAttributes.Private);

            PropertyBuilder propertyBuilder = a_TypeBuilder.DefineProperty(a_PropertyName, PropertyAttributes.HasDefault, a_PropertyType, null);
            MethodBuilder getPropMthdBldr = a_TypeBuilder.DefineMethod("get_" + a_PropertyName,
                                                        MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
                                                        a_PropertyType, Type.EmptyTypes);

            ILGenerator getIl = getPropMthdBldr.GetILGenerator();

            // Load the current instance onto the stack
            getIl.Emit(OpCodes.Ldarg_0);
            // Loads the value of the field specified as parameter from the object on the stack
            getIl.Emit(OpCodes.Ldfld, fieldBuilder);
            // Returns the method and pushes the get value onto the caller's stack
            getIl.Emit(OpCodes.Ret);

            MethodBuilder setPropMthdBldr = a_TypeBuilder.DefineMethod("set_" + a_PropertyName,
                                                        MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
                                                        null, new[] { a_PropertyType });

            ILGenerator setIl = setPropMthdBldr.GetILGenerator();
            // Load the current instance onto the stack
            setIl.Emit(OpCodes.Ldarg_0);
            // Load the first argument, which is the assignment value onto the stack
            setIl.Emit(OpCodes.Ldarg_1);
            // Store the value currently on the stack in the field specified as parameter in the object on the stack
            setIl.Emit(OpCodes.Stfld, fieldBuilder);
            // Returns the setter
            setIl.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
        private static void MakeProperty(TypeBuilder typeBuilder, string name, Type type)
        {
            var fieldBuilder = typeBuilder.DefineField("_" + name, type, FieldAttributes.Private);
            var propertyBuilder = typeBuilder.DefineProperty(name, PropertyAttributes.None, CallingConventions.HasThis, type,
                                                             null);
            var getSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;

            var getter = typeBuilder.DefineMethod("get_" + name, getSetAttr, type, Type.EmptyTypes);

            var getIL = getter.GetILGenerator();
            getIL.Emit(OpCodes.Ldarg_0);
            getIL.Emit(OpCodes.Ldfld, fieldBuilder);
            getIL.Emit(OpCodes.Ret);

            var setter = typeBuilder.DefineMethod("set_" + name, getSetAttr, null, new[] {type});

            var setIL = setter.GetILGenerator();
            setIL.Emit(OpCodes.Ldarg_0);
            setIL.Emit(OpCodes.Ldarg_1);
            setIL.Emit(OpCodes.Stfld, fieldBuilder);
            setIL.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getter);
            propertyBuilder.SetSetMethod(setter);
        }
Example #13
0
        private static FieldInfo[] GenerateProperties(TypeBuilder tb, IDictionary<string, Type> properties)
        {
            const MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;

            FieldInfo[] fields = new FieldBuilder[properties.Count];
            int i = 0;
            foreach (string key in properties.Keys)
            {
                string name = key;
                Type type = properties[key];
                FieldBuilder fb = tb.DefineField("_" + key, type, FieldAttributes.Public);
                PropertyBuilder pb = tb.DefineProperty(key, PropertyAttributes.HasDefault, type, null);
                
                MethodBuilder mbGet = tb.DefineMethod("get_" + name, getSetAttr, type, Type.EmptyTypes);
                ILGenerator genGet = mbGet.GetILGenerator(8);
                genGet.Emit(OpCodes.Ldarg_0);
                genGet.Emit(OpCodes.Ldfld, fb);
                genGet.Emit(OpCodes.Ret);
                pb.SetGetMethod(mbGet);

                MethodBuilder mbSet = tb.DefineMethod("set_" + name, getSetAttr, null, new Type[] { type });
                ILGenerator genSet = mbSet.GetILGenerator(8);
                genSet.Emit(OpCodes.Ldarg_0);
                genSet.Emit(OpCodes.Ldarg_1);
                genSet.Emit(OpCodes.Stfld, fb);
                genSet.Emit(OpCodes.Ret);
                pb.SetSetMethod(mbSet);

                fields[i] = fb;
            }

            return fields;
        }
Example #14
0
        private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
        {
            FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);

            PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
            MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
            ILGenerator getIl = getPropMthdBldr.GetILGenerator();

            getIl.Emit(OpCodes.Ldarg_0);
            getIl.Emit(OpCodes.Ldfld, fieldBuilder);
            getIl.Emit(OpCodes.Ret);

            MethodBuilder setPropMthdBldr =
                tb.DefineMethod("set_" + propertyName,
                  MethodAttributes.Public |
                  MethodAttributes.SpecialName |
                  MethodAttributes.HideBySig,
                  null, new[] { propertyType });

            ILGenerator setIl = setPropMthdBldr.GetILGenerator();
            Label modifyProperty = setIl.DefineLabel();
            Label exitSet = setIl.DefineLabel();

            setIl.MarkLabel(modifyProperty);
            setIl.Emit(OpCodes.Ldarg_0);
            setIl.Emit(OpCodes.Ldarg_1);
            setIl.Emit(OpCodes.Stfld, fieldBuilder);

            setIl.Emit(OpCodes.Nop);
            setIl.MarkLabel(exitSet);
            setIl.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
        private PropertyBuilder CreatePropertyProxyBuilder(TypeBuilder typeBuilder, PropertyInfo contractProperty)
        {
            var builder = typeBuilder.DefineProperty(contractProperty.Name, contractProperty.Attributes,
                                                     contractProperty.PropertyType, null);

            return builder;
        }
Example #16
0
        private void ImplementInterfaceProperties(Type interfaceOfTypeToCreate, System.Reflection.Emit.TypeBuilder typeBuilder)
        {
            typeBuilder.AddInterfaceImplementation(interfaceOfTypeToCreate);
            foreach (var implementedInterfaceType in interfaceOfTypeToCreate.GetInterfaces())
            {
                ImplementInterfaceProperties(implementedInterfaceType, typeBuilder);
            }

            foreach (var pi in interfaceOfTypeToCreate.GetProperties())
            {
                var backingFieldBuilder = typeBuilder.DefineField($"{interfaceOfTypeToCreate.Name}._{ToCamelCase(pi.Name)}", pi.PropertyType, FieldAttributes.Private);

                var accessorAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.Virtual | MethodAttributes.HideBySig;

                var mbGetAccessor = typeBuilder.DefineMethod($"get_{pi.Name}", accessorAttributes, pi.PropertyType, Type.EmptyTypes);
                var mbGetIL       = mbGetAccessor.GetILGenerator();
                mbGetIL.Emit(OpCodes.Ldarg_0);
                mbGetIL.Emit(OpCodes.Ldfld, backingFieldBuilder);
                mbGetIL.Emit(OpCodes.Ret);

                var mbSetAccessor = typeBuilder.DefineMethod($"set_{pi.Name}", accessorAttributes, null, new[] { pi.PropertyType });
                var mbSetIL       = mbSetAccessor.GetILGenerator();
                mbSetIL.Emit(OpCodes.Ldarg_0);
                mbSetIL.Emit(OpCodes.Ldarg_1);
                mbSetIL.Emit(OpCodes.Stfld, backingFieldBuilder);
                mbSetIL.Emit(OpCodes.Ret);

                var propertyBuilder = typeBuilder.DefineProperty(pi.Name, PropertyAttributes.HasDefault, pi.PropertyType, null);
                propertyBuilder.SetGetMethod(mbGetAccessor);
                propertyBuilder.SetSetMethod(mbSetAccessor);
            }
        }
Example #17
0
		private FieldInfo[] GenerateProperties(TypeBuilder tb, DynamicProperty[] properties)
		{
			FieldInfo[] array = new FieldBuilder[properties.Length];
			for (int i = 0; i < properties.Length; i++)
			{
				DynamicProperty dynamicProperty = properties[i];
				FieldBuilder fieldBuilder = tb.DefineField("_" + dynamicProperty.Name, dynamicProperty.Type, FieldAttributes.Private);
				PropertyBuilder propertyBuilder = tb.DefineProperty(dynamicProperty.Name, PropertyAttributes.HasDefault, dynamicProperty.Type, null);
				MethodBuilder methodBuilder = tb.DefineMethod("get_" + dynamicProperty.Name, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName, dynamicProperty.Type, Type.EmptyTypes);
				ILGenerator iLGenerator = methodBuilder.GetILGenerator();
				iLGenerator.Emit(OpCodes.Ldarg_0);
				iLGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
				iLGenerator.Emit(OpCodes.Ret);
				MethodBuilder methodBuilder2 = tb.DefineMethod("set_" + dynamicProperty.Name, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName, null, new Type[]
				{
					dynamicProperty.Type
				});
				ILGenerator iLGenerator2 = methodBuilder2.GetILGenerator();
				iLGenerator2.Emit(OpCodes.Ldarg_0);
				iLGenerator2.Emit(OpCodes.Ldarg_1);
				iLGenerator2.Emit(OpCodes.Stfld, fieldBuilder);
				iLGenerator2.Emit(OpCodes.Ret);
				propertyBuilder.SetGetMethod(methodBuilder);
				propertyBuilder.SetSetMethod(methodBuilder2);
				array[i] = fieldBuilder;
			}
			return array;
		}
Example #18
0
		public PropertyEmitter(TypeBuilder owner, string name, Type propertyType, FieldBuilder propertyChangedField) {
			this.owner = owner;
			this.propertyChangedField = propertyChangedField;
			fieldBuilder = owner.DefineField(String.Format("<{0}>", name), propertyType, FieldAttributes.Private);
			getterBuilder = owner.DefineMethod(String.Format("get_{0}", name), MethodAttributes.Public|MethodAttributes.Virtual|MethodAttributes.HideBySig|MethodAttributes.SpecialName, propertyType, Type.EmptyTypes);
			ILGenerator getterIl = getterBuilder.GetILGenerator();
			getterIl.Emit(OpCodes.Ldarg_0);
			getterIl.Emit(OpCodes.Ldfld, fieldBuilder);
			getterIl.Emit(OpCodes.Ret);
			setterBuilder = owner.DefineMethod(String.Format("set_{0}", name), MethodAttributes.Public|MethodAttributes.Virtual|MethodAttributes.HideBySig|MethodAttributes.SpecialName, typeof(void), new[] {propertyType});
			ILGenerator setterIl = setterBuilder.GetILGenerator();
			setterIl.Emit(OpCodes.Ldarg_0);
			setterIl.Emit(OpCodes.Ldarg_1);
			setterIl.Emit(OpCodes.Stfld, fieldBuilder);
			if (propertyChangedField != null) {
				setterIl.Emit(OpCodes.Ldarg_0);
				setterIl.Emit(OpCodes.Dup);
				setterIl.Emit(OpCodes.Ldfld, propertyChangedField);
				setterIl.Emit(OpCodes.Ldstr, name);
				setterIl.Emit(OpCodes.Call, proxyBase_NotifyPropertyChanged);
			}
			setterIl.Emit(OpCodes.Ret);
			propertyBuilder = owner.DefineProperty(name, PropertyAttributes.None, propertyType, null);
			propertyBuilder.SetGetMethod(getterBuilder);
			propertyBuilder.SetSetMethod(setterBuilder);
		}
        private static void CreateProperty(TypeBuilder typeBuilder, string name, Type type)
        {
            var fieldBuilder = typeBuilder.DefineField("_" + name.ToLower(), type, FieldAttributes.Private);
            var propertyBuilder = typeBuilder.DefineProperty(name, PropertyAttributes.HasDefault, type, null);

            propertyBuilder.SetGetMethod(CreateGetMethod(typeBuilder, fieldBuilder, name, type));
            propertyBuilder.SetSetMethod(CreateSetMethod(typeBuilder, fieldBuilder, name, type));
        }
 public static void DefineProperty(TypeBuilder typeBuilder, PropertyInfo propertyInfo,
     MethodBuilder getMethodBuilder, MethodBuilder setMethodBuilder)
 {
     String propertyName = propertyInfo.DeclaringType.FullName + "." + propertyInfo.Name;
     PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, propertyInfo.PropertyType, Type.EmptyTypes);
     if (getMethodBuilder != null)
         propertyBuilder.SetGetMethod(getMethodBuilder);
     if (setMethodBuilder != null)
         propertyBuilder.SetSetMethod(setMethodBuilder);
 }
        public void DefineProperty(TypeBuilder builder, Type type, string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("propertyName");
            }

            string fieldName = Char.ToLowerInvariant(name[0]) + name.Substring(1);
            string propertyName = Char.ToUpperInvariant(name[0]) + name.Substring(1);

            FieldBuilder fieldBuilder = builder.DefineField(
                fieldName,
                type,
                FieldAttributes.Private);

            PropertyBuilder propertyBuilder = builder.DefineProperty(
                propertyName,
                PropertyAttributes.HasDefault,
                type, 
                null);

            //Getter
            MethodBuilder getMethodBuilder = builder.DefineMethod(
                "get_" + propertyName, 
                MethodAttributes.Public |
                MethodAttributes.SpecialName |
                MethodAttributes.HideBySig,
                type, 
                Type.EmptyTypes);

            ILGenerator getILGenerator = getMethodBuilder.GetILGenerator();

            getILGenerator.Emit(OpCodes.Ldarg_0);
            getILGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
            getILGenerator.Emit(OpCodes.Ret);

            //Setter
            MethodBuilder setMethodBuilder = builder.DefineMethod(
                "set_" + propertyName, 
                MethodAttributes.Public |
                MethodAttributes.SpecialName |
                MethodAttributes.HideBySig, 
                null,
                new Type[] { type });

            ILGenerator setILGenerator = setMethodBuilder.GetILGenerator();

            setILGenerator.Emit(OpCodes.Ldarg_0);
            setILGenerator.Emit(OpCodes.Ldarg_1);
            setILGenerator.Emit(OpCodes.Stfld, fieldBuilder);
            setILGenerator.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getMethodBuilder);
            propertyBuilder.SetSetMethod(setMethodBuilder);
        }
Example #22
0
        private static void CreateProperty(System.Reflection.Emit.TypeBuilder tb, string propertyName, Type propertyType, bool required)
        {
            if (propertyType.IsByRef)
            {
                //avoids an exception in code below when by ref parameters are used
                propertyType = propertyType.GetElementType();
            }

            FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);

            PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
            MethodBuilder   getPropMthdBldr = tb.DefineMethod("get_" + propertyName,
                                                              MethodAttributes.Public | MethodAttributes.SpecialName |
                                                              MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
            ILGenerator getIl = getPropMthdBldr.GetILGenerator();

            getIl.Emit(OpCodes.Ldarg_0);
            getIl.Emit(OpCodes.Ldfld, fieldBuilder);
            getIl.Emit(OpCodes.Ret);

            MethodBuilder setPropMthdBldr =
                tb.DefineMethod("set_" + propertyName,
                                MethodAttributes.Public |
                                MethodAttributes.SpecialName |
                                MethodAttributes.HideBySig,
                                null, new[] { propertyType });

            ILGenerator setIl          = setPropMthdBldr.GetILGenerator();
            Label       modifyProperty = setIl.DefineLabel();
            Label       exitSet        = setIl.DefineLabel();

            setIl.MarkLabel(modifyProperty);
            setIl.Emit(OpCodes.Ldarg_0);
            setIl.Emit(OpCodes.Ldarg_1);
            setIl.Emit(OpCodes.Stfld, fieldBuilder);

            setIl.Emit(OpCodes.Nop);
            setIl.MarkLabel(exitSet);
            setIl.Emit(OpCodes.Ret);

            Type[]          ctorParams     = { };
            ConstructorInfo contructorInfo = typeof(DataMemberAttribute).GetConstructor(ctorParams);

            CustomAttributeBuilder customAttrBuilder = new CustomAttributeBuilder(contructorInfo, new object[] { });

            //TODO: set IsRequired here ??

            propertyBuilder.SetCustomAttribute(customAttrBuilder);

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
Example #23
0
        /// <summary>把lcpi参数里的属性加入到myTypeBuilder中。注意:该操作会将其它成员清除掉,其功能有待完善。</summary>
        /// <param name="typeBuilder">类型构造器的实例。</param>
        /// <param name="cpis">里面包含属性列表的信息。</param>
        private static void AddPropertyToTypeBuilder(System.Reflection.Emit.TypeBuilder typeBuilder, List <CustPropertyInfo> cpis)
        {
            PropertyBuilder  custNamePropBldr;
            MethodBuilder    custNameGetPropMthdBldr;
            MethodBuilder    custNameSetPropMthdBldr;
            MethodAttributes getSetAttr;
            ILGenerator      custNameGetIL;
            ILGenerator      custNameSetIL;

            // 属性Set和Get方法要一个专门的属性。这里设置为Public。
            getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;

            // 添加属性到myTypeBuilder。
            foreach (CustPropertyInfo cpi in cpis)
            {
                // 定义字段。
                FieldBuilder customerNameBldr = typeBuilder.DefineField(cpi.FieldName, Type.GetType(cpi.Type), FieldAttributes.Private);
                customerNameBldr.SetConstant("11111111");

                // 定义属性。 最后一个参数为null,因为属性没有参数。
                custNamePropBldr = typeBuilder.DefineProperty(cpi.PropertyName, PropertyAttributes.HasDefault, Type.GetType(cpi.Type), null);
                custNamePropBldr.SetConstant("111111111");

                // 定义Get方法。
                custNameGetPropMthdBldr = typeBuilder.DefineMethod(cpi.GetPropertyMethodName, getSetAttr, Type.GetType(cpi.Type), Type.EmptyTypes);
                custNameGetIL           = custNameGetPropMthdBldr.GetILGenerator();
                try
                {
                    custNameGetIL.Emit(OpCodes.Ldarg_0);
                    //custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);
                    custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);
                    custNameGetIL.Emit(OpCodes.Ret);
                }
                catch
                {
                }

                //定义Set方法。
                custNameSetPropMthdBldr = typeBuilder.DefineMethod(cpi.SetPropertyMethodName, getSetAttr, null, new Type[] { Type.GetType(cpi.Type) });
                custNameSetIL           = custNameSetPropMthdBldr.GetILGenerator();
                custNameSetIL.Emit(OpCodes.Ldarg_0);
                custNameSetIL.Emit(OpCodes.Ldarg_1);
                custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr);
                custNameSetIL.Emit(OpCodes.Ret);
                //custNamePropBldr.SetConstant("ceshi");
                //把创建的两个方法(Get,Set)加入到PropertyBuilder中。
                custNamePropBldr.SetGetMethod(custNameGetPropMthdBldr);
                custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr);
            }
        }
Example #24
0
        /// <summary>
        /// Adds a new property o the runtime class
        /// </summary>
        /// <param name="typebuilder"></param>
        /// <param name="propertyName">name of the property</param>
        /// <param name="typeOfProperty">type of the property</param>
        private static void AddProperty(TypeBuilder typebuilder, string propertyName, Type typeOfProperty)
        {
            // Generate a private field
            FieldBuilder field = typebuilder.DefineField("_" + propertyName, typeOfProperty, FieldAttributes.Private);
            // Generate a public property
            PropertyBuilder property =
                typebuilder.DefineProperty(propertyName,
                                 PropertyAttributes.None,
                                 typeOfProperty,
                                 new Type[] { typeOfProperty });

            // The property set and property get methods require a special set of attributes:

            MethodAttributes GetSetAttr =
                MethodAttributes.Public |
                MethodAttributes.HideBySig;

            // Define the "get" accessor method for current private field.
            MethodBuilder currGetPropMthdBldr =
                typebuilder.DefineMethod("get_value",
                                           GetSetAttr,
                                           typeOfProperty,
                                           Type.EmptyTypes);

            // Intermediate Language stuff...
            ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
            currGetIL.Emit(OpCodes.Ldarg_0);
            currGetIL.Emit(OpCodes.Ldfld, field);
            currGetIL.Emit(OpCodes.Ret);

            // Define the "set" accessor method for current private field.
            MethodBuilder currSetPropMthdBldr =
                typebuilder.DefineMethod("set_value",
                                           GetSetAttr,
                                           null,
                                           new Type[] { typeOfProperty });

            // Again some Intermediate Language stuff...
            ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
            currSetIL.Emit(OpCodes.Ldarg_0);
            currSetIL.Emit(OpCodes.Ldarg_1);
            currSetIL.Emit(OpCodes.Stfld, field);
            currSetIL.Emit(OpCodes.Ret);

            // Last, we must map the two methods created above to our PropertyBuilder to
            // their corresponding behaviors, "get" and "set" respectively.
            property.SetGetMethod(currGetPropMthdBldr);
            property.SetSetMethod(currSetPropMthdBldr);
        }
Example #25
0
        /// <summary>
        /// Create property with explicit implementation of getter and setter, with no method defined.
        /// </summary>
        private PropertyDefinition AddProperty(TypeDefinition declaringType,
                                               string name,
                                               TypeReference propertyType,
                                               string explicitPrefix,
                                               PropertyInfo overridedProp)
        {
            var proxyPropDef = declaringType.DefineProperty(explicitPrefix + name,
                                                            PropertyAttributes.None | PropertyAttributes.SpecialName,
                                                            propertyType,
                                                            null);
            const MethodAttributes methodAttributes = MethodAttributes.Private
                                                      | MethodAttributes.HideBySig
                                                      | MethodAttributes.NewSlot
                                                      | MethodAttributes.Virtual
                                                      | MethodAttributes.Final
                                                      | MethodAttributes.SpecialName;

            var overridedGetMethod = overridedProp.GetGetMethod();

            if (overridedGetMethod != null)
            {
                var proxyPropGetter = declaringType.DefineMethod(
                    $"{explicitPrefix}get_{name}",
                    methodAttributes,
                    propertyType,
                    Type.EmptyTypes);
                declaringType.DefineMethodOverride(proxyPropGetter, overridedGetMethod);

                proxyPropDef.SetGetMethod(proxyPropGetter);
            }

            var overridedSetMethod = overridedProp.GetSetMethod();

            if (overridedSetMethod != null)
            {
                var proxyPropSetter = declaringType.DefineMethod(
                    $"{explicitPrefix}set_{name}",
                    methodAttributes,
                    null,
                    new[] { propertyType });

                proxyPropSetter.DefineParameter(0, ParameterAttributes.None, "value");
                declaringType.DefineMethodOverride(proxyPropSetter, overridedSetMethod);
                proxyPropDef.SetSetMethod(proxyPropSetter);
            }

            return(proxyPropDef);
        }
Example #26
0
        private void AddProperty(TypeBuilder builder, string propertyName, Type propertyType)
        {
            string fieldName = String.Format("_{0}", propertyName);
            Type type = propertyType;
            if (type.IsValueType)
            {
                type = GetNullableType(type);
            }
            FieldBuilder fieldBuilder = builder.DefineField(fieldName, type, FieldAttributes.Private);
            PropertyBuilder propertyBuilder =
                builder.DefineProperty(propertyName, PropertyAttributes.None, type,
                                       Type.EmptyTypes);

            const MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName |
                                                MethodAttributes.HideBySig;

            MethodBuilder getPropertyMethodBuilder =
                builder.DefineMethod(
                    String.Format("get_{0}", propertyName),
                    getSetAttr,
                    type,
                    Type.EmptyTypes);

            ILGenerator propertyNameGetIL = getPropertyMethodBuilder.GetILGenerator();

            propertyNameGetIL.Emit(OpCodes.Ldarg_0);
            propertyNameGetIL.Emit(OpCodes.Ldfld, fieldBuilder);
            propertyNameGetIL.Emit(OpCodes.Ret);

            MethodBuilder custNameSetPropMthdBldr =
                builder.DefineMethod(
                    String.Format("set_{0}", propertyName),
                    getSetAttr,
                    null,
                    new[] {type});

            ILGenerator propertyNameSetIL = custNameSetPropMthdBldr.GetILGenerator();

            propertyNameSetIL.Emit(OpCodes.Ldarg_0);
            propertyNameSetIL.Emit(OpCodes.Ldarg_1);
            propertyNameSetIL.Emit(OpCodes.Stfld, fieldBuilder);
            propertyNameSetIL.Emit(OpCodes.Ret);


            propertyBuilder.SetGetMethod(getPropertyMethodBuilder);
            propertyBuilder.SetSetMethod(custNameSetPropMthdBldr);
        }
Example #27
0
        private static void AddProperty(TypeBuilder typeBuilder, Type baseType, string propertyName, Type propertyType)
        {
            var fieldBuilder = typeBuilder.DefineField(propertyName + Guid.NewGuid(),
                                                       propertyType,
                                                       FieldAttributes.Private);

            var propertyBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);

            // TODO: fix
            //var customAttributeBuilder = new CustomAttributeBuilder(typeof (RequiredAttribute).GetConstructor(Type.EmptyTypes), new object[0]);
            //propertyBuilder.SetCustomAttribute(customAttributeBuilder);

            const MethodAttributes getSetAttributes = MethodAttributes.Public
                                                    | MethodAttributes.SpecialName
                                                    | MethodAttributes.HideBySig;

            var getPropertyValueMethod =
                typeof (BusinessObject<>).MakeGenericType(baseType).GetMethod("GetProperty",
                                                                              BindingFlags.NonPublic |
                                                                              BindingFlags.Instance)
                                                                   .MakeGenericMethod(propertyType);
            var getMethodBuilder = typeBuilder.DefineMethod("get_" + propertyName, getSetAttributes, propertyType, Type.EmptyTypes);
            ILGenerator getGenerator = getMethodBuilder.GetILGenerator();
            getGenerator.Emit(OpCodes.Ldarg_0);
            getGenerator.Emit(OpCodes.Ldstr, propertyName);
            getGenerator.Emit(OpCodes.Ldarg_0);
            getGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
            getGenerator.Emit(OpCodes.Call, getPropertyValueMethod);
            getGenerator.Emit(OpCodes.Ret);
            propertyBuilder.SetGetMethod(getMethodBuilder);

            var setPropertyValueMethod =
                typeof (BusinessObject<>).MakeGenericType(baseType).GetMethod("SetProperty",
                                                                              BindingFlags.NonPublic |
                                                                              BindingFlags.Instance)
                                                                   .MakeGenericMethod(propertyType);
            var setMethodBuilder = typeBuilder.DefineMethod("set_" + propertyName, getSetAttributes, null, new[] { propertyType });
            ILGenerator setGenerator = setMethodBuilder.GetILGenerator();
            setGenerator.Emit(OpCodes.Ldarg_0);
            setGenerator.Emit(OpCodes.Ldstr, propertyName);
            setGenerator.Emit(OpCodes.Ldarg_0);
            setGenerator.Emit(OpCodes.Ldflda, fieldBuilder);
            setGenerator.Emit(OpCodes.Ldarg_1);
            setGenerator.Emit(OpCodes.Call, setPropertyValueMethod);
            setGenerator.Emit(OpCodes.Ret);
            propertyBuilder.SetSetMethod(setMethodBuilder);
        }
Example #28
0
        private static void CreateDecoratedProperty(TypeBuilder tb, PropertyInfo prop, Type decoratorType, string decoratedPropertyName, Type decoratedType)
        {
            var propertyName = prop.Name;
            var propertyType = prop.PropertyType;

            var propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.None, propertyType, null);

            foreach (var builder in prop.GetCustomAttributesData().Select(GetAttributeCopy))
                propertyBuilder.SetCustomAttribute(builder);

            var getPropMthdBldr = tb.DefineMethod("get_" + propertyName,
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType,
                Type.EmptyTypes);

            var getIl = getPropMthdBldr.GetILGenerator();
            getIl.Emit(OpCodes.Ldarg_0);
            getIl.Emit(OpCodes.Castclass, decoratorType);
            getIl.Emit(OpCodes.Callvirt, decoratorType.GetProperty(decoratedPropertyName,
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetGetMethod(true));
            getIl.Emit(OpCodes.Callvirt, decoratedType.GetProperty(propertyName,
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetGetMethod(true));
            getIl.Emit(OpCodes.Ret);

            var setPropMthdBldr = tb.DefineMethod("set_" + propertyName,
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null,
                new[] { propertyType });

            propertyBuilder.SetGetMethod(getPropMthdBldr);

            var setIl = setPropMthdBldr.GetILGenerator();

            //var modifyProperty = setIl.DefineLabel();
            //var exitSet = setIl.DefineLabel();
            //setIl.MarkLabel(modifyProperty);
            setIl.Emit(OpCodes.Ldarg_0);
            //setIl.Emit(OpCodes.Castclass, decoratorType);
            setIl.Emit(OpCodes.Callvirt, decoratorType.GetProperty(decoratedPropertyName,
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetGetMethod(true));
            setIl.Emit(OpCodes.Ldarg_1);
            setIl.Emit(OpCodes.Callvirt, decoratedType.GetProperty(propertyName,
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetSetMethod(true));
            //setIl.Emit(OpCodes.Nop);
            //setIl.MarkLabel(exitSet);
            setIl.Emit(OpCodes.Ret);

            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
		internal CodeProperty (CodeClass cls, string name, PropertyAttributes attributes, MethodAttributes methodAttributes, Type returnType, Type[] parameterTypes) 
		{
			this.cls = cls;
			this.typeBuilder = cls.TypeBuilder;
			this.name = name;
			this.attributes = attributes;
			this.methodAttributes = methodAttributes;
			this.returnType = returnType;
			this.parameterTypes = parameterTypes;
		
			PropertyBuilder pb = typeBuilder.DefineProperty (name, attributes, returnType, parameterTypes);
			pb.SetGetMethod (typeBuilder.DefineMethod ("get_" + name, methodAttributes, CallingConventions.Standard, returnType, Type.EmptyTypes));
			pb.SetSetMethod (typeBuilder.DefineMethod ("set_" + name, methodAttributes, CallingConventions.Standard, typeof (void), new Type [] {returnType}));
			get_builder = new CodeBuilder (cls);
			set_builder = new CodeBuilder (cls);
			propertyInfo = pb;
		}
Example #30
0
        /// <summary>
        /// Creates the property.
        /// </summary>
        /// <param name="typeBuilder">The type builder.</param>
        /// <param name="prop">The prop.</param>
        public static void CreateProperty(TypeBuilder typeBuilder, PropertyInfo prop)
        {
            var fieldBuilder = typeBuilder.DefineField(
                "field_" + prop.Name,
                prop.PropertyType,
                FieldAttributes.Private);

            var propBuilder = typeBuilder.DefineProperty(
                prop.Name,
                prop.Attributes | PropertyAttributes.HasDefault,
                prop.PropertyType,
                null);

            SetDataMemberAttribute(propBuilder);

            CreateGetMethod(typeBuilder, prop, fieldBuilder, propBuilder);
            CreateSetMethod(typeBuilder, prop, fieldBuilder, propBuilder);
        }
        private void CreateProperty(TypeBuilder typeBuilder, PropertyInfo interfaceProperty)
        {
            var propertyName = interfaceProperty.Name;

            var field = typeBuilder.DefineField(
                propertyName,
                interfaceProperty.PropertyType,
                FieldAttributes.Private);

            var property = typeBuilder.DefineProperty(
                propertyName,
                PropertyAttributes.None,
                interfaceProperty.PropertyType,
                new[] { interfaceProperty.PropertyType });

            var getMethodBuilder = typeBuilder.DefineMethod(
                "get_value",
                DuckMethodAttributes,
                interfaceProperty.PropertyType,
                Type.EmptyTypes);

            var getGenerator = getMethodBuilder.GetILGenerator();
            getGenerator.Emit(OpCodes.Ldarg_0);
            getGenerator.Emit(OpCodes.Ldfld, field);
            getGenerator.Emit(OpCodes.Ret);

            var setMethodBuilder = typeBuilder.DefineMethod(
                "set_value",
                DuckMethodAttributes,
                null,
                new[] { interfaceProperty.PropertyType });

            var setGenerator = setMethodBuilder.GetILGenerator();
            setGenerator.Emit(OpCodes.Ldarg_0);
            setGenerator.Emit(OpCodes.Ldarg_1);
            setGenerator.Emit(OpCodes.Stfld, field);
            setGenerator.Emit(OpCodes.Ret);

            property.SetGetMethod(getMethodBuilder);
            property.SetSetMethod(setMethodBuilder);

            typeBuilder.DefineMethodOverride(getMethodBuilder, interfaceProperty.GetGetMethod());
            typeBuilder.DefineMethodOverride(setMethodBuilder, interfaceProperty.GetSetMethod());
        }
        private static void CreateProperty(TypeBuilder typeBuilder, XomNodeAttribute attribute)
        {
            var attributeType = attribute.Type;
            if (attributeType.IsValueType && !attribute.IsRequired)
                attributeType = typeof (Nullable<>).MakeGenericType(attributeType);

            var fieldBuilder = typeBuilder.DefineField("_" + attribute.Name, attributeType, FieldAttributes.Private);
            var propertyBuilder = typeBuilder.DefineProperty(attribute.Name, PropertyAttributes.HasDefault,
                                                             attributeType, null);

            var getPropMthdBldr = typeBuilder.DefineMethod("get_" + attribute.Name,
                                                           MethodAttributes.Public | MethodAttributes.SpecialName |
                                                           MethodAttributes.HideBySig, attributeType, Type.EmptyTypes);

            var getIl = getPropMthdBldr.GetILGenerator();

            getIl.Emit(OpCodes.Ldarg_0);
            getIl.Emit(OpCodes.Ldfld, fieldBuilder);
            getIl.Emit(OpCodes.Ret);

            MethodBuilder setPropMthdBldr =
                typeBuilder.DefineMethod("set_" + attribute.Name,
                  MethodAttributes.Public |
                  MethodAttributes.SpecialName |
                  MethodAttributes.HideBySig,
                  null, new[] { attributeType });

            ILGenerator setIl = setPropMthdBldr.GetILGenerator();
            Label modifyProperty = setIl.DefineLabel();
            Label exitSet = setIl.DefineLabel();

            setIl.MarkLabel(modifyProperty);
            setIl.Emit(OpCodes.Ldarg_0);
            setIl.Emit(OpCodes.Ldarg_1);
            setIl.Emit(OpCodes.Stfld, fieldBuilder);

            setIl.Emit(OpCodes.Nop);
            setIl.MarkLabel(exitSet);
            setIl.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);
        }
Example #33
0
 /// <summary>
 /// Adds a new property to the type builder, with getter and setter to a generated field.
 /// </summary>
 /// <param name="typeBuilder">The type builder.</param>
 /// <param name="propertyName">Name of the property.</param>
 /// <param name="propertyType">Type of the property.</param>
 public static void AddProperty(TypeBuilder typeBuilder, string propertyName, Type propertyType)
 {
     const MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig;
     FieldBuilder field = typeBuilder.DefineField("_" + propertyName, typeof(string), FieldAttributes.Private);
     PropertyBuilder property = typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, propertyType, new[] { propertyType });
     MethodBuilder getMethodBuilder = typeBuilder.DefineMethod("get_value", getSetAttr, propertyType, Type.EmptyTypes);
     ILGenerator getIl = getMethodBuilder.GetILGenerator();
     getIl.Emit(OpCodes.Ldarg_0);
     getIl.Emit(OpCodes.Ldfld, field);
     getIl.Emit(OpCodes.Ret);
     MethodBuilder setMethodBuilder = typeBuilder.DefineMethod("set_value", getSetAttr, null, new[] { propertyType });
     ILGenerator setIl = setMethodBuilder.GetILGenerator();
     setIl.Emit(OpCodes.Ldarg_0);
     setIl.Emit(OpCodes.Ldarg_1);
     setIl.Emit(OpCodes.Stfld, field);
     setIl.Emit(OpCodes.Ret);
     property.SetGetMethod(getMethodBuilder);
     property.SetSetMethod(setMethodBuilder);
 }
Example #34
0
    public static Type BuildPropertyObject(System.Collections.Generic.IEnumerable <System.Collections.Generic.KeyValuePair <string, Type> > obj)
    {
        string nameOfDLL      = "magic.dll";
        string nameOfAssembly = "magic_Assembly";
        string nameOfModule   = "magic_Module";
        string nameOfType     = "magic_Type";

        System.Reflection.AssemblyName assemblyName = new System.Reflection.AssemblyName {
            Name = nameOfAssembly
        };
        System.Reflection.Emit.AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave);
        System.Reflection.Emit.ModuleBuilder   moduleBuilder   = assemblyBuilder.DefineDynamicModule(nameOfModule, nameOfDLL);
        System.Reflection.Emit.TypeBuilder     typeBuilder     = moduleBuilder.DefineType(nameOfType, System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Class);
        foreach (var prop in obj)
        {
            string Name     = prop.Key;
            Type   DataType = prop.Value;
            System.Reflection.Emit.FieldBuilder    field               = typeBuilder.DefineField("_" + Name, DataType, System.Reflection.FieldAttributes.Private);
            System.Reflection.Emit.PropertyBuilder propertyBuilder     = typeBuilder.DefineProperty(Name, System.Reflection.PropertyAttributes.SpecialName, DataType, null);
            System.Reflection.MethodAttributes     methodAttributes    = System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.HideBySig | System.Reflection.MethodAttributes.SpecialName;
            System.Reflection.Emit.MethodBuilder   methodBuilderGetter = typeBuilder.DefineMethod("get_" + Name, methodAttributes, DataType, new Type[] { });
            System.Reflection.Emit.MethodBuilder   methodBuilderSetter = typeBuilder.DefineMethod("set_" + Name, methodAttributes, typeof(void), new Type[] { DataType });
            System.Reflection.Emit.ILGenerator     ilGeneratorGetter   = methodBuilderGetter.GetILGenerator();
            ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
            ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
            ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ret);
            System.Reflection.Emit.ILGenerator ilGeneratorSetter = methodBuilderSetter.GetILGenerator();
            ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
            ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
            ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Stfld, field);
            ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ret);
            propertyBuilder.SetGetMethod(methodBuilderGetter);
            propertyBuilder.SetSetMethod(methodBuilderSetter);
        }
        // Yes! you must do this, it should not be needed but it is!
        Type dynamicType = typeBuilder.CreateType();

        // Save to file
        assemblyBuilder.Save(nameOfDLL);
        return(dynamicType);
    }
        public IConstructorArg Define(TypeBuilder tb)
        {
            FieldBuilder fieldBuilder = tb.DefineField("_" + Name, ParameterType, FieldAttributes.Private);

            PropertyBuilder propertyBuilder = tb.DefineProperty(Name, PropertyAttributes.HasDefault, ParameterType, null);
            MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
                ParameterType, Type.EmptyTypes);
            ILGenerator getIl = getPropMthdBldr.GetILGenerator();

            getIl.Emit(OpCodes.Ldarg_0);
            getIl.Emit(OpCodes.Ldfld, fieldBuilder);
            getIl.Emit(OpCodes.Ret);

            var methodAttributes = MethodAttributes.Private |
                                   MethodAttributes.SpecialName |
                                   MethodAttributes.HideBySig;
            MethodBuilder setPropMthdBldr =
                tb.DefineMethod("set_" + Name,
                    methodAttributes,
                    null, new[] { ParameterType });

            ILGenerator setIl = setPropMthdBldr.GetILGenerator();
            Label modifyProperty = setIl.DefineLabel();
            Label exitSet = setIl.DefineLabel();

            setIl.MarkLabel(modifyProperty);
            setIl.Emit(OpCodes.Ldarg_0);
            setIl.Emit(OpCodes.Ldarg_1);
            setIl.Emit(OpCodes.Stfld, fieldBuilder);

            setIl.Emit(OpCodes.Nop);
            setIl.MarkLabel(exitSet);
            setIl.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropMthdBldr);
            propertyBuilder.SetSetMethod(setPropMthdBldr);

            return new InjectableConstructorArg(ParameterType, Name, getPropMthdBldr, setPropMthdBldr);
        }
        public static void Generate(
            TypeBuilder typeBuilder,
            PropertyMetadata propertyMetadata, 
            MethodBuilder getMethod,
            MethodBuilder setMethod)
        {
            var property = typeBuilder.DefineProperty(
                propertyMetadata.Name,
                propertyMetadata.PropertyAttributes,
                propertyMetadata.PropertyType,
                propertyMetadata.IndexerTypes);

            if (getMethod != null)
            {
                property.SetGetMethod(getMethod);
            }

            if (setMethod != null)
            {
                property.SetSetMethod(setMethod);
            }
        }
        public static PropertyBuilder CreateProperty(TypeBuilder inputbuilder, string propertyname, Type propertytype)
        {
            PropertyBuilder propBuilder = inputbuilder.DefineProperty(propertyname, PropertyAttributes.None, propertytype, null);
            FieldBuilder fieldBuilder = inputbuilder.DefineField(string.Format("<>dynamicfield_{0}", propertyname), propertytype, FieldAttributes.Private);
            MethodBuilder setValue = inputbuilder.DefineMethod(string.Format("Set_{0}", propertyname), MethodAttributes.Public, typeof(void), new Type[] { propertytype });
            MethodBuilder getValue = inputbuilder.DefineMethod(string.Format("Get_{0}", propertyname), MethodAttributes.Public, propertytype, null);

            ILGenerator setMethodIL = setValue.GetILGenerator();
            setMethodIL.Emit(OpCodes.Ldarg, 0);
            setMethodIL.Emit(OpCodes.Ldarg, 1);
            setMethodIL.Emit(OpCodes.Stfld, fieldBuilder);
            setMethodIL.Emit(OpCodes.Ret);
            propBuilder.SetSetMethod(setValue);

            ILGenerator getMethodIL = getValue.GetILGenerator();
            getMethodIL.Emit(OpCodes.Ldarg, 0);
            getMethodIL.Emit(OpCodes.Ldfld, fieldBuilder);
            getMethodIL.Emit(OpCodes.Ret);
            propBuilder.SetGetMethod(getValue);

            return propBuilder;
        }
Example #38
0
        /// <summary>
        /// Generate the declaration for the IgnoresAccessChecksToAttribute type.
        /// This attribute will be both defined and used in the dynamic assembly.
        /// Each usage identifies the name of the assembly containing non-public
        /// types the dynamic assembly needs to access.  Normally those types
        /// would be inaccessible, but this attribute allows them to be visible.
        /// It works like a reverse InternalsVisibleToAttribute.
        /// This method returns the ConstructorInfo of the generated attribute.
        /// </summary>
        public static ConstructorInfo AddToModule(ModuleBuilder mb)
        {
            TypeBuilder attributeTypeBuilder =
                mb.DefineType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute",
                              TypeAttributes.Public | TypeAttributes.Class,
                              typeof(Attribute));

            // Create backing field as:
            // private string assemblyName;
            FieldBuilder assemblyNameField =
                attributeTypeBuilder.DefineField("assemblyName", typeof(string), FieldAttributes.Private);

            // Create ctor as:
            // public IgnoresAccessChecksToAttribute(string)
            ConstructorBuilder constructorBuilder = attributeTypeBuilder.DefineConstructor(MethodAttributes.Public,
                                                                                           CallingConventions.HasThis,
                                                                                           new Type[] { assemblyNameField.FieldType });

            ILGenerator il = constructorBuilder.GetILGenerator();

            // Create ctor body as:
            // this.assemblyName = {ctor parameter 0}
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg, 1);
            il.Emit(OpCodes.Stfld, assemblyNameField);

            // return
            il.Emit(OpCodes.Ret);

            // Define property as:
            // public string AssemblyName {get { return this.assemblyName; } }
            _ = attributeTypeBuilder.DefineProperty(
                "AssemblyName",
                PropertyAttributes.None,
                CallingConventions.HasThis,
                returnType: typeof(string),
                parameterTypes: null);

            MethodBuilder getterMethodBuilder = attributeTypeBuilder.DefineMethod(
                "get_AssemblyName",
                MethodAttributes.Public,
                CallingConventions.HasThis,
                returnType: typeof(string),
                parameterTypes: null);

            // Generate body:
            // return this.assemblyName;
            il = getterMethodBuilder.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, assemblyNameField);
            il.Emit(OpCodes.Ret);

            // Generate the AttributeUsage attribute for this attribute type:
            // [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
            TypeInfo attributeUsageTypeInfo = typeof(AttributeUsageAttribute).GetTypeInfo();

            // Find the ctor that takes only AttributeTargets
            ConstructorInfo attributeUsageConstructorInfo =
                attributeUsageTypeInfo.DeclaredConstructors
                .Single(c => c.GetParameters().Length == 1 &&
                        c.GetParameters()[0].ParameterType == typeof(AttributeTargets));

            // Find the property to set AllowMultiple
            PropertyInfo allowMultipleProperty =
                attributeUsageTypeInfo.DeclaredProperties
                .Single(f => string.Equals(f.Name, "AllowMultiple"));

            // Create a builder to construct the instance via the ctor and property
            CustomAttributeBuilder customAttributeBuilder =
                new CustomAttributeBuilder(attributeUsageConstructorInfo,
                                           new object[] { AttributeTargets.Assembly },
                                           new PropertyInfo[] { allowMultipleProperty },
                                           new object[] { true });

            // Attach this attribute instance to the newly defined attribute type
            attributeTypeBuilder.SetCustomAttribute(customAttributeBuilder);

            // Make the TypeInfo real so the constructor can be used.
            return(attributeTypeBuilder.CreateTypeInfo() !.DeclaredConstructors.Single());
        }
Example #39
0
        /// <summary>
        /// Compiles the type that is being built and returns its run-time Type.
        /// If you want to create instances directly, see the GetConstructorDelegate.
        /// </summary>
        public Type Compile()
        {
            if (_compiledType == null)
            {
                _CheckThread();

                _delegates = new Delegate[_methods.Count];

                var methodBuilders = new Dictionary <string, MethodBuilder>();
                int index          = -1;
                foreach (var method in _methods)
                {
                    index++;
                    var methodBuilder = _Compile(method, index);
                    methodBuilders[method.Name] = methodBuilder;
                }

                foreach (var property in _properties.Values)
                {
                    string name            = property.Name;
                    var    propertyBuilder = _type.DefineProperty(name, PropertyAttributes.None, property.PropertyType, Type.EmptyTypes);
                    propertyBuilder.SetGetMethod(methodBuilders["get_" + name]);
                    propertyBuilder.SetSetMethod(methodBuilders["set_" + name]);
                }

                foreach (var eventInfo in _events.Values)
                {
                    string name         = eventInfo.Name;
                    var    eventBuilder = _type.DefineEvent(name, EventAttributes.None, eventInfo.Type);

                    string addName    = "add_" + name;
                    string removeName = "remove_" + name;

                    var addMethod    = methodBuilders[addName];
                    var removeMethod = methodBuilders[removeName];
                    eventBuilder.SetAddOnMethod(addMethod);
                    eventBuilder.SetRemoveOnMethod(removeMethod);

                    foreach (var interfaceType in _interfaceTypes)
                    {
                        var method = interfaceType.GetMethod(addName);
                        if (method != null)
                        {
                            _type.DefineMethodOverride(addMethod, method);
                        }

                        method = interfaceType.GetMethod(removeName);
                        if (method != null)
                        {
                            _type.DefineMethodOverride(removeMethod, method);
                        }
                    }
                }

                var compiledType = _type.CreateType();

                var thisExpression = Expression.Parameter(compiledType, "this");
                var fields         = _fields.ToArray();
                foreach (var fieldPair in fields)
                {
                    var    leftPair   = fieldPair.Key;
                    var    field      = leftPair.Key;
                    var    rightPair  = fieldPair.Value;
                    string fieldName  = rightPair.Value;
                    var    expression = Expression.MakeMemberAccess(thisExpression, compiledType.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic));
                    _fields[leftPair] = new KeyValuePair <MemberExpression, string>(expression, fieldName);
                }

                index = -1;
                foreach (var method in _methods)
                {
                    index++;

                    if (method._respectVisibility)
                    {
                        continue;
                    }

                    if (!method.IsStatic)
                    {
                        var firstParameter = method._parameters.Keys.First();
                        method._parameters[firstParameter] = thisExpression;
                    }

                    var compiledMethod = method._Compile(null, null);
                    _delegates[index] = compiledMethod;
                }

                var delegatesField = compiledType.GetField(".delegates", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
                delegatesField.SetValue(null, _delegates);

                _compiledType = compiledType;
            }

            return(_compiledType);
        }
Example #40
0
 public static PropertyBuilder DefineProperty(this TypeBuilder tb, string name, PropertyAttributes attributes, CallingConventions callingConvention, GenericTypeParameterBuilder returnType, Type[] parameterTypes)
 {
     return(tb.DefineProperty(name, attributes, callingConvention, returnType.AsType(), parameterTypes));
 }