Get named values from a Fody CustomAttribute Constructor

35 Views Asked by At

Can anyone tell me how to read the property assignments of a CustomAttribute's constructor

[Display(Name = "This name and value")]

They don't seem to appear in either theattribute.ConstructorArguments or theAttribute.Properties (which is always empty).

1

There are 1 best solutions below

0
Peter Morris On BEST ANSWER
private CustomAttribute CloneAttribute(CustomAttribute sourceAttribute)
{
    MethodReference sourceAttributeConstructor = sourceAttribute.Constructor;
    MethodReference localAttributeConstructorReference = ModuleDefinition.ImportReference(sourceAttributeConstructor);

    var localCustomAttribute = new CustomAttribute(localAttributeConstructorReference);
    foreach (var sourceAttributeConstructorArgument in sourceAttribute.ConstructorArguments)
    {
        TypeReference localAttributeTypeReference = sourceAttributeConstructorArgument.Type;
        CustomAttributeArgument localAttributeInstance = new CustomAttributeArgument(localAttributeTypeReference, sourceAttributeConstructorArgument.Value);
        localCustomAttribute.ConstructorArguments.Add(localAttributeInstance);
    }

    // This was the piece of missing code
    foreach(var sourceAttributePropertArgument in sourceAttribute.Properties)
    {
        var localAttributePropertyArgument = new CustomAttributeNamedArgument(name: sourceAttributePropertArgument.Name, argument: sourceAttributePropertArgument.Argument);
        localCustomAttribute.Properties.Add(localAttributePropertyArgument);
    }

    return localCustomAttribute;
}