public DefineField ( string fieldName, System type, System attributes ) : System.Reflection.Emit.FieldBuilder | ||
fieldName | string | |
type | System | |
attributes | System | |
Résultat | System.Reflection.Emit.FieldBuilder |
private void DefineClassVaribale(Emit.TypeBuilder typeBuilder, TypeDeclaration _type) { fieldList = new Dictionary <string, Emit.FieldBuilder>(); Emit.FieldBuilder classVariable; foreach (KeyValuePair <string, Type> para in _type.instanceVariable) { classVariable = typeBuilder.DefineField(para.Key, para.Value, FieldAttributes.Private); fieldList.Add(para.Key, classVariable); } foreach (KeyValuePair <string, Type> para in _type.classVariable) { classVariable = typeBuilder.DefineField(para.Key, para.Value, FieldAttributes.Private | FieldAttributes.Static); fieldList.Add(para.Key, classVariable); } //mthdIL.Emit(OpCodes.Ldarg_0); //mthdIL.Emit(OpCodes.Ldarg_0); //mthdIL.Emit(OpCodes.Ldfld, balanceAmtBldr); //mthdIL.Emit(OpCodes.Ldarg_2); //mthdIL.Emit(OpCodes.Add); }
public BFMemory(TypeBuilder typeBuilder) { PointerFieldBuilder = typeBuilder.DefineField("pointer", typeof(short), FieldAttributes.Static | FieldAttributes.Private); MemoryFieldBuilder = typeBuilder.DefineField("memory", typeof(byte[]), FieldAttributes.Static | FieldAttributes.Private); var staticConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Static,CallingConventions.Standard, null); GenerateStaticConstructorBody(staticConstructorBuilder.GetILGenerator()); }
public ProxyClassFieldCache(TypeBuilder typeBuilder) { this.typeBuilder = typeBuilder; manualCodecFields = new Dictionary<Type, FieldBuilder>(); Processor = typeBuilder.DefineField("methodCallProcessor", typeof(IOutgoingRequestProcessor), FieldAttributes.Private | FieldAttributes.InitOnly); Scope = typeBuilder.DefineField("scope", typeof(string), FieldAttributes.Private | FieldAttributes.InitOnly); TimeoutSettings = typeBuilder.DefineField("timeoutSettings", typeof(TimeoutSettings), FieldAttributes.Private | FieldAttributes.InitOnly); CodecContainer = typeBuilder.DefineField("codecContainer", typeof(ICodecContainer), FieldAttributes.Private | FieldAttributes.InitOnly); }
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); } }
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); }
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); }
public void CreateDynamicMethod() { #if SAVE_ASSEMBLY if (_assemblyBuilder == null) { AssemblyName assemblyName = new AssemblyName("ExpressionAssembly"); _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, "I:\\Trash"); _moduleBuilder = _assemblyBuilder.DefineDynamicModule("ExpressionModule", "ExpressionModule.module"); } string typeName = String.Format("Expression{0}", _typeCount); _typeCount++; _typeBuilder = _moduleBuilder.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public); FieldBuilder filedBuilder = _typeBuilder.DefineField("Source", typeof(string), FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal); filedBuilder.SetConstant(_source); _methodBuilder = _typeBuilder.DefineMethod("Evaluate", MethodAttributes.Public | MethodAttributes.Static, typeof(object), new Type[] { typeof(object[]) }); _ilGenerator = _methodBuilder.GetILGenerator(); #else _dynamicMethod = new DynamicMethod("Expression", typeof(object), new Type[] { typeof(object[]) }, GetType().Module); _ilGenerator = _dynamicMethod.GetILGenerator(); #endif }
static void DefineDelegateFieldAndOverride(TypeBuilder tb, int numArgs) { Type fieldType = FuncTypeHelpers.GetFFuncType(numArgs); string fieldName = "_fn" + numArgs; FieldBuilder fb = tb.DefineField(fieldName, fieldType, FieldAttributes.Public); MethodBuilder mb = tb.DefineMethod("invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual, typeof(object), CreateObjectTypeArray(numArgs)); ILGenerator gen = mb.GetILGenerator(); Label eqLabel = gen.DefineLabel(); // this._fni == null ? gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, fb); gen.Emit(OpCodes.Ldnull); gen.Emit(OpCodes.Beq, eqLabel); //Not equal to Null, invoke it. gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, fb); for (int i = 0; i < numArgs; i++) gen.Emit(OpCodes.Ldarg, i+1); gen.Emit(OpCodes.Call,fb.FieldType.GetMethod("Invoke")); gen.Emit(OpCodes.Ret); gen.MarkLabel(eqLabel); // Equal to Null: throw WrongArityException gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Call, Method_AFn_WrongArityException); gen.Emit(OpCodes.Throw); }
public void genVariable(Symbol s) { Emit.FieldBuilder fbuilder = typeBuilder.DefineField(s.Name, getSystemTypeFormat(s.Type), Reflect.FieldAttributes.Private | Reflect.FieldAttributes.Static); fbuilderTable.Add(s.Name, fbuilder); }
/// <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); }
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 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; }
internal static Dictionary<string, FieldBuilder> Build(TypeBuilder proxyBuilder, Type proxyType) { return new Dictionary<string, FieldBuilder> { { ProxyFieldBuilder.InvokeHandlerField, proxyBuilder.DefineField( ProxyFieldBuilder.InvokeHandlerField, typeof(IInvocationHandler[]), FieldAttributes.Private) }, { ProxyFieldBuilder.WrappedObjectField, proxyBuilder.DefineField( ProxyFieldBuilder.WrappedObjectField, proxyType, FieldAttributes.Private) } }; }
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); }
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; }
/// <summary> /// Adds a new field to the class, with the given name, attributes and field type. /// </summary> /// <param name="fieldName">The name of the field. <paramref name="fieldName"/> cannot contain embedded nulls.</param> /// <param name="type">The type of the field.</param> /// <param name="attributes">The attributes of the field.</param> /// <returns>The defined field.</returns> public FieldBuilder DefineField( string fieldName, Type type, FieldAttributes attributes) { return(_typeBuilder.DefineField(fieldName, type, attributes)); }
public void ImplementProxy(TypeBuilder typeBuilder) { // Implement the IProxy interface typeBuilder.AddInterfaceImplementation(typeof (IProxy)); field = typeBuilder.DefineField("__interceptor", typeof (IInterceptor), FieldAttributes.Private); // Implement the getter MethodBuilder getterMethod = typeBuilder.DefineMethod("get_Interceptor", InterceptorMethodsAttributes, CallingConventions.HasThis, typeof(IInterceptor), new System.Type[0]); getterMethod.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.IL); ILGenerator IL = getterMethod.GetILGenerator(); // This is equivalent to: // get { return __interceptor; IL.Emit(OpCodes.Ldarg_0); IL.Emit(OpCodes.Ldfld, field); IL.Emit(OpCodes.Ret); // Implement the setter MethodBuilder setterMethod = typeBuilder.DefineMethod("set_Interceptor", InterceptorMethodsAttributes, CallingConventions.HasThis, typeof (void), new[] {typeof (IInterceptor)}); setterMethod.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.IL); IL = setterMethod.GetILGenerator(); IL.Emit(OpCodes.Ldarg_0); IL.Emit(OpCodes.Ldarg_1); IL.Emit(OpCodes.Stfld, field); IL.Emit(OpCodes.Ret); MethodInfo originalSetter = typeof (IProxy).GetMethod("set_Interceptor"); MethodInfo originalGetter = typeof (IProxy).GetMethod("get_Interceptor"); typeBuilder.DefineMethodOverride(setterMethod, originalSetter); typeBuilder.DefineMethodOverride(getterMethod, originalGetter); }
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); }
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 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); }
public AbstractProxyBuilder(ModuleBuilder moduleBuilder, string className, Type interfaceType, Type innerType) { Verify.ArgumentNotNull(moduleBuilder, "moduleBuilder"); Verify.ArgumentNotNull(className, "className"); Verify.ArgumentNotNull(interfaceType, "interfaceType"); Verify.ArgumentNotNull(innerType, "innerType"); if (!interfaceType.IsInterface) { throw new ArgumentException("must be an interface type", "interfaceType"); } _errorMessages = new List<string>(); _moduleBuilder = moduleBuilder; _className = className; _interfaceType = interfaceType; _innerType = innerType; _typeBuilder = _moduleBuilder.DefineType( _className, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, typeof(object), new Type[] {_interfaceType}); _innerFieldBuilder = _typeBuilder.DefineField("inner", _innerType, FieldAttributes.Private); }
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); }
/// <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; }
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; }
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); }
public void ImplementProxy(TypeBuilder typeBuilder) { typeBuilder.AddInterfaceImplementation(typeof (IProxy)); InterceptorField = typeBuilder .DefineField("__interceptor", typeof (Proxy.DynamicProxy.IInterceptor), FieldAttributes.Private); var getterMethod = typeBuilder .DefineMethod("get_Interceptor", InterceptorMethodsAttributes, CallingConventions.HasThis, typeof (Proxy.DynamicProxy.IInterceptor), new System.Type[0]); getterMethod.SetImplementationFlags(MethodImplAttributes.IL); var il = getterMethod.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, InterceptorField); il.Emit(OpCodes.Ret); var setterMethod = typeBuilder .DefineMethod("set_Interceptor", InterceptorMethodsAttributes, CallingConventions.HasThis, typeof (void), new[] {typeof (Proxy.DynamicProxy.IInterceptor)}); setterMethod.SetImplementationFlags(MethodImplAttributes.IL); il = setterMethod.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Stfld, InterceptorField); il.Emit(OpCodes.Ret); var originalSetter = typeof (IProxy).GetMethod("set_Interceptor"); var originalGetter = typeof (IProxy).GetMethod("get_Interceptor"); typeBuilder.DefineMethodOverride(setterMethod, originalSetter); typeBuilder.DefineMethodOverride(getterMethod, originalGetter); }
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 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)); }
protected virtual unsafe FieldBuilder DefineField(TypeBuilder typeBuilder, BCSYM_Variable* pField) { string fieldName = new string(*((char**) (pField + 12))); BCSYM* pSymbol = BCSYM.DigThroughNamedType(*((BCSYM* modopt(IsConst) modopt(IsConst)*) (pField + 80))); Type type = this.GetType(typeBuilder, pSymbol); FieldAttributes fieldAttributes = GetFieldAttributes(pField); return typeBuilder.DefineField(fieldName, type, fieldAttributes); }
private void BuildFields(TypeBuilder typeBuilder) { foreach (string str in this._parser.SymbolTable.Variables.Keys) { FieldInfo info = typeBuilder.DefineField(str, typeof(Primitive), FieldAttributes.Static | FieldAttributes.Private); this._currentScope.Fields.Add(str, info); } }
private void CreateFields(Type sourceType, TypeBuilder typeBuilder) { var fieldMap = SnapshotableField.GetMap(sourceType); foreach (var pair in fieldMap) { typeBuilder.DefineField(pair.Key, pair.Value.FieldType, FieldAttributes.Public); } }
internal EnumBuilder (ModuleBuilder mb, string name, TypeAttributes visibility, Type underlyingType) { _tb = new TypeBuilder (mb, name, (visibility | TypeAttributes.Sealed), typeof(Enum), null, PackingSize.Unspecified, 0, null); _underlyingType = underlyingType; _underlyingField = _tb.DefineField ("value__", underlyingType, (FieldAttributes.SpecialName | FieldAttributes.Private | FieldAttributes.RTSpecialName)); setup_enum_type (_tb); }
private EnumeratorCompiler(Type t, ModuleBuilder module) { var et = typeof(IEnumerator<>).MakeGenericType(t); _tBuilder = module.DefineType("DbEnumerator_" + t.Name, TypeAttributes.Class | TypeAttributes.Public, null, new[] { et }); _fldCls = _tBuilder.DefineField("_cols", typeof(int[]), FieldAttributes.Private); _fldCur = _tBuilder.DefineField("_current", t, FieldAttributes.Private); _fldRdr = _tBuilder.DefineField("_rdr", t, FieldAttributes.Private); var fields = new List<PropertyInfo>(); foreach (var member in t.GetMembers()) { if (!(member is PropertyInfo)) continue; var property = (PropertyInfo) member; if (property.CanWrite && property.GetSetMethod().IsPublic) fields.Add(property); } _fields = fields.ToArray(); }
public InjectedTypeBuilder(TypeBuilder typeBuilder) { if (typeBuilder == null) throw new ArgumentNullException("typeBuilder"); _typeBuilder = typeBuilder; _injectionSetField = typeBuilder.DefineField("_injectionSet", typeof(InjectionSet), FieldAttributes.Private | FieldAttributes.InitOnly); }
private static FieldBuilder GenerateField(TypeBuilder typeBuilder, FieldMetadata fieldMetadata) { var field = typeBuilder.DefineField( fieldMetadata.Name, fieldMetadata.FieldType, fieldMetadata.FieldAttributes); return field; }
public virtual void Implement(TypeBuilder typeBuilder, Action<FieldBuilder, bool> registerField) { // Add instance field to store IEntityWrapper instance // The field is typed as object, for two reasons: // 1. The practical one, IEntityWrapper is internal and not accessible from the dynamic assembly. // 2. We purposely want the wrapper field to be opaque on the proxy type. var wrapperField = typeBuilder.DefineField(EntityProxyTypeInfo.EntityWrapperFieldName, typeof(object), FieldAttributes.Public); registerField(wrapperField, false); }
/// <summary> /// Adds a new field to this type. You should give an expression that access a local /// variable, as this will be marked as the local variable that represents the field /// in all other calls. /// </summary> public void AddField <T>(string fieldName, Expression <Func <T> > expression) { if (fieldName == null) { throw new ArgumentNullException("fieldName"); } if (expression == null) { throw new ArgumentNullException("expression"); } var body = expression.Body; if (body.NodeType != ExpressionType.MemberAccess) { throw new ArgumentException("A call to AddField must access a local variable of your code to work properly."); } _CheckUncompiled(); MemberExpression memberExpression = (MemberExpression)body; MemberInfo member = memberExpression.Member; if (member.MemberType != MemberTypes.Field) { throw new ArgumentException("A call to AddField must access a local variable of your code to work properly."); } object source = null; Expression untypedSource = memberExpression.Expression; if (untypedSource != null) { if (untypedSource.NodeType != ExpressionType.Constant) { throw new ArgumentException("A call to AddField must access a local variable of your code to work properly."); } var sourceExpression = (ConstantExpression)untypedSource; source = sourceExpression.Value; } var field = (FieldInfo)member; object fieldValue = field.GetValue(source); if (!EqualityComparer <T> .Default.Equals((T)fieldValue, default(T))) { throw new ArgumentException("The local variable used to declare a field must have its default value at this moment."); } var fieldBuilder = _type.DefineField(fieldName, field.FieldType, FieldAttributes.Private); _fields.Add(new KeyValuePair <FieldInfo, object>(field, source), new KeyValuePair <MemberExpression, string>(null, fieldName)); }
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); }
/// <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); } }
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); }
/// <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()); }
public override void CreateDeclarations(System.Reflection.Emit.TypeBuilder typeBuilder) { this.Field = typeBuilder.DefineField(this.MemberName, this.MemberType, FieldAttributes.Private); }
/// <summary> /// Creates a new fluent type builder using the given name, telling if the /// generated type will be collectible (if you use the other overloads, /// this value is true) and optionally telling which interfaces should be /// implemented. /// </summary> public FluentTypeBuilder(string name, bool isCollectible, params Type[] interfaceTypes) { _delegatesExpression = () => _delegates; _creatorThreadId = Thread.CurrentThread.ManagedThreadId; _isCollectible = isCollectible; Type baseType; HashSet <Type> allInterfaces = new HashSet <Type>(); if (typeof(TBase).IsInterface) { baseType = typeof(object); allInterfaces.Add(typeof(TBase)); } else { baseType = typeof(TBase); } foreach (var interfaceType in typeof(TBase).GetInterfaces()) { allInterfaces.Add(interfaceType); } if (interfaceTypes != null) { foreach (var interfaceType in interfaceTypes) { if (interfaceType == null) { throw new ArgumentException("interfaceTypes can't contain null values.", "interfaceTypes"); } if (!interfaceType.IsInterface) { throw new ArgumentException("interfaceTypes can't contain non-interface types.", "interfaceTypes"); } if (!interfaceType.IsVisible) { throw new ArgumentException("interfaceTypes must only contain visible interfaces (public interfaces declared directly in namespaces or inside other public types).", "interfaceTypes"); } allInterfaces.Add(interfaceType); foreach (var baseInterface in interfaceType.GetInterfaces()) { allInterfaces.Add(baseInterface); } } } AssemblyBuilderAccess access = AssemblyBuilderAccess.Run; if (isCollectible) { access = AssemblyBuilderAccess.RunAndCollect; } _interfaceTypes = allInterfaces.ToArray(); var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(name), access); var module = assembly.DefineDynamicModule(name); _type = module.DefineType(name, TypeAttributes.NotPublic, baseType, _interfaceTypes); _type.DefineDefaultConstructor(MethodAttributes.Public); _delegatesField = _type.DefineField(".delegates", typeof(Delegate[]), FieldAttributes.Private | FieldAttributes.Static); }