Skip to main content
 首页 » 编程设计

c#之有没有办法在运行时获取构造函数参数的值

2024年02月13日19webabcd

我想做的是将现有的 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); 
            } 
} 

它可以工作,但仅适用于具有无参数构造函数 的属性。 例如“DataTypeAttribute”只有带有参数的构造函数。

现在我想知道是否有办法获取 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() 
    { 
 
    } 
} 

现在我只能复制 RequiredAttribute 因为它有无参数的构造函数。我无法复制 DataTypeAttribute。所以我想从我的示例模型中获取此 value DataType.Text。

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

请您参考如下方法:

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