快速访问在C#中保存属性的类型/方法/ ...

Wil*_*sem 8 c# attributes system.reflection methodinfo

我在这里创建了一个名为AAtribute的自定义属性,例如一个名为B的类,其中一个或多个方法使用该属性.是否有可能获得保存属性(在本例中为BMethod1)的方法的MethodInfo作为(其中一个)属性而不遍历整个程序集并查看其属性的所有已定义方法?它们是其他AttributeTargets(参数/类型/属性/ ...)的模拟方式吗?我不想要使用这种类型的属性的所有方法的数组,而只需要使用此Attirbute对象的方法.我想用它来对方法添加额外的约束(返回类型,参数,名称,其他属性用法......).

[AttributeUsage(AttributeTargets.Method)]
public class AAtribute : Attribute {

    //some fields and properties

    public AAtribute () {//perhaps with some parameters
        //some operations
        MethodInfo mi;//acces to the MethodInfo with this Attribute
                      //as an Attribute (the question)
        //some operations with the MethodInfo
    }

    //some methods

}

public class B {

    //some fields, properties and constructors

    [A]
    public void BMethod1 () {
        //some operations
    }

    //other methods

}
Run Code Online (Sandbox Code Playgroud)

Pao*_*sco 2

如果我正确理解您的问题,您希望在属性 code 内获取应用该属性的对象(在本例中为方法)。
我很确定没有直接的方法可以做到这一点 - 该属性不知道它所附加的对象,这种关联是相反的。

我能建议你的最好方法是像下面这样的解决方法:

using System;
using System.Reflection;

namespace test {

    [AttributeUsage(AttributeTargets.Method)]
    public class AAttribute : Attribute {
        public AAttribute(Type type,string method) {
            MethodInfo mi = type.GetMethod(method);
        }
    }

    public class B {
        [A(typeof(B),"BMethod1")]
        public void BMethod1() {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意
您希望通过访问属性构造函数内的 MethodInfo 来实现什么目的?也许有另一种方法可以实现你的目标......

编辑

作为另一种可能的解决方案,您可以在属性中提供一个静态方法来执行检查 - 但这涉及迭代 MethodInfos。

using System;
using System.Reflection;
namespace test {

    [AttributeUsage(AttributeTargets.Method)]
    public class AAttribute : Attribute {
        public static void CheckType<T>() {
            foreach (MethodInfo mi in typeof(T).GetMethods()) {
                AAttribute[] attributes = (AAttribute[])mi.GetCustomAttributes(typeof(AAttribute), false);
                if (0 != attributes.Length) {
                    // do your checks here
                }
            }
        }
    }

    public class B {
        [A]
        public void BMethod1() {
        }
        [A]
        public int BMethod2() {
            return 0;
        }
    }

    public static class Program {
        public static void Main() {
            AAttribute.CheckType<B>();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)