我想这样做:
[My]
public void F()
{
}
class MyAttribute : Attribute
{
public MyAttribute()
{
// I want the value "F" here
我该怎么做?
答案 0 :(得分:2)
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`
}
}