有没有一种方法可以在运行时获取构造函数参数的值

本文关键字:获取 运行时 构造函数 参数 方法 一种 有没有 | 更新日期: 2023-09-27 18:22:00

我要做的是将现有的attributes从一个property复制到另一个。这是我现在的代码:

foreach (var prop in typeof(Example).GetProperties())
{
            FieldBuilder field = typeBuilder.DefineField("_" + prop.Name, prop.PropertyType, FieldAttributes.Private);
            PropertyBuilder propertyBuilder =
                typeBuilder.DefineProperty(prop.Name,
                                 PropertyAttributes.HasDefault,
                                 prop.PropertyType,
                                 null);
            object[] attributes = prop.GetCustomAttributes(true);
            foreach (var attr in attributes)
            {
                //Here I need to get value of constructor parameter passed in declaration of Example class
                ConstructorInfo attributeConstructorInfo = attr.GetType().GetConstructor(new Type[]{});
                CustomAttributeBuilder customAttributeBuilder = new CustomAttributeBuilder(attributeConstructorInfo,new Type[]{});
                propertyBuilder.SetCustomAttribute(customAttributeBuilder);
            }
}

它只适用于具有无参数constructorattributes。例如,"DataTypeAttribute"只有constructorsparameter

现在我想知道是否有一种方法可以获得attribute constructor 的当前值

假设我有这个型号:

public class Example
{
    public virtual int Id { get; set; }
    [Required]
    [MaxLength(50)]
    [DataType(DataType.Text)]
    public virtual string Name { get; set; }
    [MaxLength(500)]
    public virtual string Desc { get; set; }
    public virtual string StartDt { get; set; }
    public Example()
    {
    }
}

目前,我只能使用copyRequiredAttribute,因为它有无参数的constructor。我无法copy DataTypeAttribute。所以我想从我的示例模型中得到这个valueDataType.Text

有人知道如何让它发挥作用吗?

有没有一种方法可以在运行时获取构造函数参数的值

使用GetCustomAttributesData()代替返回构造属性的GetCustomAttributes()。它返回一个CustomAttributeData的集合,其中正好包含您所需要的内容:用于创建属性的构造函数、其参数以及有关该属性的命名参数的信息。