【问题标题】:In an attribute, how can I get the name of the method it is attached to?在属性中,如何获取它所附加的方法的名称?
【发布时间】:2014-08-07 00:32:38
【问题描述】:

我想这样做:

[My]
public void F()
{
}


class MyAttribute : Attribute
{
    public MyAttribute()
    {
         // I want the value "F" here

我该怎么做?

【问题讨论】:

    标签: c# attributes metaprogramming


    【解决方案1】:

    CallerMemberName 甚至适用于属性构造函数:

        public MyAttribute([System.Runtime.CompilerServices.CallerMemberName]string methodName = null)
    

    在查询属性之前,不会实例化属性对象。

    要查看它的实际效果,请调试此程序:

    // Does not hit breakpoint
    new C().F();
    
    // does hit breakpoint
    typeof(C).GetMethod("F").GetCustomAttributes(typeof(MyAttribute), false);
    

    class MyAttribute : Attribute
    {
        public MyAttribute([System.Runtime.CompilerServices.CallerMemberName]string methodName = null)
        { // set breakpoint here and examine `methodName`
    
        }
    }
    

    【讨论】:

    • 谢谢。这可能会派上用场。
    猜你喜欢
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多