【发布时间】:2014-08-07 00:32:38
【问题描述】:
我想这样做:
[My]
public void F()
{
}
class MyAttribute : Attribute
{
public MyAttribute()
{
// I want the value "F" here
我该怎么做?
【问题讨论】:
标签: c# attributes metaprogramming
我想这样做:
[My]
public void F()
{
}
class MyAttribute : Attribute
{
public MyAttribute()
{
// I want the value "F" here
我该怎么做?
【问题讨论】:
标签: c# attributes metaprogramming
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`
}
}
【讨论】: