C#:从调用堆栈中读取特定类型的最后一个自定义属性

C#: Reading the last custom attribute of a specific type from the call stack

我想用自定义属性装饰一些函数。这些函数不会 return 特定类型,实际上可以 return 任何类型。

现在这个函数会调用任意数量的其他函数,然后在运行的某个时刻我想知道"what is the text/value last custom attribute in the call stack"。

我该怎么做?

示例:

[CustomAttribute("Hello World...")]
public void SomeFunction
{
    return Func1("myparam")
}

public void Func1(string xx)
{
    return Func2(xx)
}

public string Func2(string yy)
{
    //I would like to know what is the value\text of the attribute "CustomAttribute".
    //If there are multiples in the call stack, return the last one (which might be in another class and project as Func2)
}

如@joe Sewell 所述,总体方法是遍历 stackTrace 并检查每个方法是否具有该属性。组合 Read the value of an attribute of a method with Get stack trace 得到以下结果:

这里有一个如何操作的例子:

[System.AttributeUsage(System.AttributeTargets.Method)]
public class MyAttribute : Attribute
{
    public string Value { get; }

    public MyAttribute(string value)
    {
        Value = value;
    }

    public static string GetValueOfFirstInStackTrace()
    {
        StackTrace stackTrace = new StackTrace();           
        StackFrame[] stackFrames = stackTrace.GetFrames(); 

        foreach (var stackFrame in stackFrames)
        {
            var method = stackFrame.GetMethod();
            MyAttribute attr = (MyAttribute)method.GetCustomAttributes(typeof(MyAttribute), true).FirstOrDefault();
            if (attr != null)
            {
                string value = attr.Value;  
                return value;
            }
        }

        return null;
    }
}