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

本文关键字:动态 插入 属性 转换 CustomAttributeBuilder | 更新日期: 2023-09-27 18:14:36

我正在努力找出最好的方法来上课,如:

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;}

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

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

为属性(或任何成员)设置属性:

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 }));
相关文章: