【问题标题】:How to get all attributes and attributes data of a method using reflection in C#如何在C#中使用反射获取方法的所有属性和属性数据
【发布时间】:2015-03-27 02:15:04
【问题描述】:

最终目标是将属性“按原样”从一个方法复制到生成的类中的另一个方法。

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

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

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

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

我正在使用 CodeDom 生成代码。

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

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

    【讨论】:

    • 该代码能否区分我上面示例中的情况?
    • 是的,这就是为什么有两个 for 循环,一个用于构造函数参数,一个用于命名参数。我对这两种情况都进行了测试,并正确复制了注释。
    【解决方案2】:

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

    例如,您可能有:

    [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")]
    

    【讨论】:

    • 其实是有办法的..看下面我的回答。
    猜你喜欢
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    相关资源
    最近更新 更多