gpt4 book ai didi

c# - 在属性中,如何获取它所附加的方法的名称?

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:50 24 4
gpt4 key购买 nike

我想这样做:

[My]
public void F()
{
}


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

我该怎么做?

最佳答案

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`

}
}

关于c# - 在属性中,如何获取它所附加的方法的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24256304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com