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

C# 将现有属性转换为CustomAttributeBuilder,以便插入到动态生成的类中,c#,reflection,dynamic,attributes,custom-attributes,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 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;}

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

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

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

您是如何创建动态类的?assembly.DefinedDynamicModule(…).DefineType(…),所以我有需要CustomAttributeBuilder的构建器。我可以将SetCustomAttribute用于我想放在类型上的静态属性,但我不确定复制当前未知属性的最佳方法。