您似乎需要使用 CustomAttributeBuilder 的构造函数,它允许您指定属性及其值。你试过这个吗?
ConstructorInfo displayCtor = typeof(TestAttribute).GetConstructor(new Type[] {});
PropertyInfo conProperty = typeof (TestAttribute).GetProperty("TestProperty");
CustomAttributeBuilder displayAttrib = new CustomAttributeBuilder(displayCtor, new object[] {}, new[] {conProperty}, new object[] {"Hello"});
上面的代码适用于:
[Test(TestProperty = "Hello")]
另请注意,在您的示例中,您的属性“ ”与构造函数“ ”Display
不匹配DataValidationAttribute
编辑:
完整样本:
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
namespace SO5841769
{
class TestAttribute : Attribute
{
public string TestProperty { get; set; }
}
class Program
{
static void Main(string[] args)
{
AppDomain myDomain = Thread.GetDomain();
AssemblyName myAsmName = new AssemblyName();
myAsmName.Name = "MyDynamicAssembly";
AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(myAsmName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder myModBuilder = myAsmBuilder.DefineDynamicModule(myAsmName.Name, myAsmName.Name + ".dll");
TypeBuilder myTypeBuilder = myModBuilder.DefineType("Data", TypeAttributes.Public);
FieldBuilder someFieldBuilder = myTypeBuilder.DefineField("someField", typeof(string), FieldAttributes.Private);
PropertyBuilder somePropertyBuilder = myTypeBuilder.DefineProperty("SomeProperty", PropertyAttributes.HasDefault, typeof(string), null);
MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
ConstructorInfo displayCtor = typeof(TestAttribute).GetConstructor(new Type[] { });
PropertyInfo conProperty = typeof (TestAttribute).GetProperty("TestProperty");
CustomAttributeBuilder displayAttrib = new CustomAttributeBuilder(displayCtor, new object[] {}, new[] {conProperty}, new object[] {"Hello"});
somePropertyBuilder.SetCustomAttribute(displayAttrib);
MethodBuilder somePropertyGetPropMthdBldr = myTypeBuilder.DefineMethod("get_SomeProperty", getSetAttr, typeof(string), Type.EmptyTypes);
ILGenerator somePropertyGetIL = somePropertyGetPropMthdBldr.GetILGenerator();
somePropertyGetIL.Emit(OpCodes.Ldarg_0);
somePropertyGetIL.Emit(OpCodes.Ldfld, someFieldBuilder);
somePropertyGetIL.Emit(OpCodes.Ret);
somePropertyBuilder.SetGetMethod(somePropertyGetPropMthdBldr);
myTypeBuilder.CreateType();
myAsmBuilder.Save(myAsmName.Name + ".dll");
}
}
}