Programmatically Adding new attribute for existing class property with Reflection.Emit

对着背影说爱祢 提交于 2019-12-11 03:37:27

问题


I am trying programmatically add new attribute on top of a class member ...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;

namespace Test11
{

public class SomeAttribute : Attribute
{
    public SomeAttribute(string value)
    {
        this.Value = value;
    }

    public string Value { get; set; }
}


// for attribute to be injected the property should be "virtual"
public class ClassA
{
    public virtual int Value { get; set; }
}

public class Test
{
    public static void Func()
    {

        var type = typeof(ClassA);

        var aName = new System.Reflection.AssemblyName(Assembly.GetExecutingAssembly().GetName().Name);
        var ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run);
        var mb = ab.DefineDynamicModule(aName.Name);
        var tb = mb.DefineType(type.Name + "Proxy", System.Reflection.TypeAttributes.Public, type);

        var attrCtorParams = new Type[] { typeof(string) };
        var attrCtorInfo = typeof(SomeAttribute).GetConstructor(attrCtorParams);
        var attrBuilder = new CustomAttributeBuilder(attrCtorInfo, new object[] { "Some Value" });
        tb.SetCustomAttribute(attrBuilder);




        PropertyInfo info = typeof(ClassA).GetProperty("Value", BindingFlags.Public | BindingFlags.Instance);

        PropertyBuilder newProp = tb.DefineProperty(info.Name, PropertyAttributes.None, info.PropertyType, Type.EmptyTypes);

        newProp.SetCustomAttribute(attrBuilder);


        //var tbValue = mb.DefineType(info.Name, System.Reflection.TypeAttributes.Public, type);

        FieldBuilder ValueField = tb.DefineField("_Value", typeof(string), FieldAttributes.Private);
        MethodAttributes GetSetAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual;
        MethodBuilder ValuePropertyGet = tb.DefineMethod("get_Value", GetSetAttributes, typeof(string), Type.EmptyTypes);
        ILGenerator Generator = ValuePropertyGet.GetILGenerator();
        Generator.Emit(OpCodes.Ldarg_0);
        Generator.Emit(OpCodes.Ldfld, ValueField);
        Generator.Emit(OpCodes.Ret);

        MethodBuilder ValuePropertySet = tb.DefineMethod("set_Value", GetSetAttributes, null, new Type[] { typeof(string) });
        Generator = ValuePropertySet.GetILGenerator();
        Generator.Emit(OpCodes.Ldarg_0);
        Generator.Emit(OpCodes.Ldarg_1);
        Generator.Emit(OpCodes.Stfld, ValueField);
        Generator.Emit(OpCodes.Ret);


        newProp.SetSetMethod(ValuePropertySet);
        newProp.SetGetMethod(ValuePropertyGet);

        var newType = tb.CreateType();
        var instance = (ClassA)Activator.CreateInstance(newType);

        var attr = (SomeAttribute)instance.GetType().GetCustomAttributes(typeof(SomeAttribute), false).SingleOrDefault();

        var attr1 = (SomeAttribute)instance.Value.GetType().GetCustomAttributes(typeof(SomeAttribute), false).SingleOrDefault();

    }
}
}

This code created a proxy class for the original class. It can easily assign attribute for the entire class.

For a class property, I can replace a property with new getter and setter, assign new attribute, but my call for property GetCustomAttribute returns always NULL


回答1:


This line:

var attr1 = (SomeAttribute)instance.Value.GetType().GetCustomAttributes(typeof(SomeAttribute), false).SingleOrDefault();

Is looking for the SomeAttribute attribute on the type of Value (an int), not the new Property.

Essentially, you are doing

typeof(int).GetCustomAttributes(typeof(SomeAttribute), false).SingleOrDefault();

Which will, for obvious reasons, return null.

It should be:

var attr1 = (SomeAttribute)instance.GetType().GetProperty(nameof(instance.Value), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly).GetCustomAttributes(typeof(SomeAttribute), false).SingleOrDefault();


来源:https://stackoverflow.com/questions/49701038/programmatically-adding-new-attribute-for-existing-class-property-with-reflectio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!