Question

What I'm trying to do is copy existing attributes from one property to another. Here is my code for now:

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

It's working but only for attributes which have parameterless constructor. For e.g. "DataTypeAttribute" have only constructors with parameter.

Now I wondering if there is a way to get current value of attribute constructor

Let's say I have this model:

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()
    {

    }
}

For now I'm able to copy only RequiredAttribute because it has parameterless constructor. I'm unable to copy DataTypeAttribute. So I would like to get this value DataType.Text from my example model.

Anyone have some ideas how to make it work?

Était-ce utile?

La solution

Instead of GetCustomAttributes(), which returns constructed attributes, use GetCustomAttributesData(). It returns a collection of CustomAttributeData, which contains exactly what you need: the constructor used to create the attribute, its arguments and also information about named arguments of the attribute.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top