将现有属性转换为CustomAttributeBuilder以插入动态生成的类

时间:2011-11-15 17:48:12

标签: c# reflection dynamic attributes custom-attributes

我正在试图弄清楚什么是最好的方式,如:

public class ModelX {
    [TheAttribute(1, "two")]
    [SomeOtherAttribute(Three.Four)]
    public string Foo {get;set;}

将这些复制到

public class DynamicallyCreatedModelX {
    [TheAttribute(1, "two")]
    [SomeOtherAttribute(Three.Four)]
    public string Foo {get;set;}

我不是将数据从已知数据传递到动态类的最佳方法。

1 个答案:

答案 0 :(得分:0)

设置属性(或任何成员)的属性可以是这样的:

PropertyBuilder property = typeBuilder.DefineProperty(...);
property.SetCustomAttribute(new CustomAttributeBuilder(typeof(TheAttribute).GetConstructor(new Type[] { typeof(int), typeof(string) }), new object[] { 1, "two" }));
property.SetCustomAttribute(new CustomAttributeBuilder(typeof(SomeOtherAttribute).GetConstructor(new Type[] { typeof(Three.Four) }), new object[] { Three.Four }));