【问题标题】:C#: Reading the last custom attribute of a specific type from the call stackC#:从调用堆栈中读取特定类型的最后一个自定义属性
【发布时间】:2020-08-03 03:21:01
【问题描述】:

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

现在这个函数将调用任意数量的其他函数,然后在操作中的某个时刻我想知道“调用堆栈中的文本/值最后一个自定义属性是什么”。

我该怎么做?

例子:

[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)
}

【问题讨论】:

  • 在运行时处理自定义属性通常涉及System.Reflection API。我建议首先编写代码来获取您知道的特定硬编码方法的CustomAttribute 值。然后,您可以修改该代码以搜索 System.Diagnostics.StackTrace 类的实例。

标签: c# custom-attributes


【解决方案1】:

正如@joe Sewell 所提到的,总体方法是遍历 stackTrace 并检查每个方法是否具有该属性。将Read the value of an attribute of a methodGet 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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-05
    • 2016-03-18
    • 1970-01-01
    • 2015-09-01
    • 2015-08-05
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    相关资源
    最近更新 更多