コード例 #1
0
        /// <summary>
        /// Adds a public automatic property.
        /// </summary>
        /// <param name="typeDefinition">The type definition.</param>
        /// <param name="name">The name.</param>
        /// <param name="typeReference">The type reference.</param>
        /// <param name="moduleDefinition">The module definition.</param>
        /// <param name="typeResolver">The type resolver.</param>
        internal static void AddPublicAutoProperty(this TypeDef typeDefinition, string name, ITypeDefOrRef typeReference, ModuleDef moduleDefinition, TypeResolver typeResolver)
        {
            var compilerGeneratedAttribute = moduleDefinition.SafeImport(typeof(CompilerGeneratedAttribute));
            // backing field
            var backingFieldDefinition = new FieldDefUser($"<{name}>k__BackingField", new FieldSig(typeReference.ToTypeSig()), FieldAttributes.Private);

            backingFieldDefinition.CustomAttributes.Add(moduleDefinition.CreateCustomAttribute(compilerGeneratedAttribute, typeResolver));
            typeDefinition.Fields.Add(backingFieldDefinition);
            // property...
            var propertyDefinition = new PropertyDefUser(name, new PropertySig(true, typeReference.ToTypeSig()));

            typeDefinition.Properties.Add(propertyDefinition);
            // ...setter
            propertyDefinition.SetMethod = CreatePropertyMethod("set_" + name, moduleDefinition.CorLibTypes.Void, Tuple.Create(typeReference.ToTypeSig(), "value"));
            propertyDefinition.SetMethod.CustomAttributes.Add(moduleDefinition.CreateCustomAttribute(compilerGeneratedAttribute, typeResolver));
            typeDefinition.Methods.Add(propertyDefinition.SetMethod);
            var setterParameter = new ParamDefUser("value");

            propertyDefinition.SetMethod.ParamDefs.Add(setterParameter);
            var setterInstructions = new Instructions(propertyDefinition.SetMethod.Body.Instructions, moduleDefinition);

            setterInstructions.Emit(OpCodes.Ldarg_0);
            setterInstructions.Emit(OpCodes.Ldarg_1);
            setterInstructions.Emit(OpCodes.Stfld, backingFieldDefinition);
            setterInstructions.Emit(OpCodes.Ret);
            // ...getter
            propertyDefinition.GetMethod = CreatePropertyMethod("get_" + name, typeReference.ToTypeSig());
            propertyDefinition.GetMethod.CustomAttributes.Add(moduleDefinition.CreateCustomAttribute(compilerGeneratedAttribute, typeResolver));
            typeDefinition.Methods.Add(propertyDefinition.GetMethod);
            var getterInstructions = new Instructions(propertyDefinition.GetMethod.Body.Instructions, moduleDefinition);

            getterInstructions.Emit(OpCodes.Ldarg_0);
            getterInstructions.Emit(OpCodes.Ldfld, backingFieldDefinition);
            getterInstructions.Emit(OpCodes.Ret);
        }