简体   繁体   中英

How to get all attributes and attributes data of a method using reflection in C#

The end goal is to copy the attributes "as is" from a method to another method in a generated class.

public class MyOriginalClass
{
    [Attribute1]
    [Attribute2("value of attribute 2")]
    void MyMethod(){}
}

public class MyGeneratedClass
{
    [Attribute1]
    [Attribute2("value of attribute 2")]
    void MyGeneratedMethod(){}
}

I am able to list the attribute of the method using MethodInfo.GetCustomAttributes() however, this does not give me the attributes arguments; which I need to generate the corresponding attribute on the generated class.

Note that I don't know the type of the attributes (can't cast the Attribute).

I am using CodeDom to generate code.

MethodInfo.GetCustomAttributesData() has the needed information:

// method is the MethodInfo reference
// member is CodeMemberMethod (CodeDom) used to generate the output method; 
foreach (CustomAttributeData attributeData in method.GetCustomAttributesData())
{
    var arguments = new List<CodeAttributeArgument>();
    foreach (var argument in attributeData.ConstructorArguments)
    {
        arguments.Add(new CodeAttributeArgument(new CodeSnippetExpression(argument.ToString())));
    }

    if (attributeData.NamedArguments != null)
        foreach (var argument in attributeData.NamedArguments)
        {
            arguments.Add(new CodeAttributeArgument(new CodeSnippetExpression(argument.ToString())));
        }

    member.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(attributeData.AttributeType), arguments.ToArray()));
}

I don't see how it would be possible to do this. GetCustomAttributes returns an array of objects, each of which is an instance of a custom attribute. There's no way to know which constructor was used to create that instance, so there's no way to know how to create the code for such a constructor (which is what the attribute syntax amounts to).

For instance, you might have:

[Attribute2("value of attribute 2")]
void MyMethod(){}

Attribute2 may be defined as:

public class Attribute2 : Attribute {
    public Attribute2(string value) { }
    public Attribute2() {}
    public string Value{get;set;}
}

There's no way to know if it was generated by

[Attribute2("value of attribute 2")]

or by

[Attribute2(Value="value of attribute 2")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM