如何在C#中使用反射获取方法的所有属性和属性数据

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

最终目标是将属性 "as is" 从一个方法复制到生成的 class 中的另一个方法。

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

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

我可以使用 MethodInfo.GetCustomAttributes() 列出方法的属性,但是,这并没有给我属性参数;我需要在生成的 class 上生成相应的属性。

请注意,我不知道属性的类型(无法转换属性)。

我正在使用 CodeDom 生成代码。

我不知道如何做到这一点。 GetCustomAttributes returns 一个对象数组,每个对象都是一个自定义属性的实例。无法知道使用哪个构造函数来创建该实例,因此无法知道如何为此类构造函数创建代码(这就是属性语法的含义)。

例如,您可能有:

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

Attribute2 可以定义为:

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

无法知道它是否由

生成
[Attribute2("value of attribute 2")]

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

MethodInfo.GetCustomAttributesData() 有需要的信息:

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