簡體   English   中英

如何檢查是否在 StackFrame 中定義了類屬性?

[英]How to check if class attribute defined in StackFrame?

我需要在我的 exeption 中間件中跳過我classSystem.Diagnostics.StackFrame路由。

目前,如果我的方法具有[StackTraceHidden]屬性,我可以檢查異常StackFrame

例如,這就是我的類現在的樣子(屬性需要標記每個方法):

public class ValidString
{
    private string _value;

    [StackTraceHidden]
    public ValidString(string value)
    {
        Validate(value);
        _value = value;
    }

    [StackTraceHidden]
    private void Validate(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
            throw new ArgumentException(nameof(value));  
    }

    [StackTraceHidden]
    public static implicit operator ValidString(string value)
    {
        if (value == null)
            return null;

        return new ValidString(value);
    }
}

以及我如何跳過StackFrame中的標記方法:

    foreach(StackFrame stackFrame in stackTrace.GetFrames())
        if (!stackFrame.GetMethod().IsDefined(typeof(StackTraceHiddenAttribute), true))
            return stackFrame;

用這些屬性標記我需要跳過的類的每個方法感覺不對。 我想用[StackTraceHidden]屬性標記我的class以跳過在class注冊的所有StackFrame

這就是我想要的樣子(屬性只標記類):

[StackTraceHidden]
public class ValidString
{
    private string _value;

    public ValidString(string value)
    {
        Validate(value);
        _value = value;
    }

    private void Validate(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
            throw new ArgumentException(nameof(value));
    }

    public static implicit operator ValidString(string value)
    {
        if (value == null)
            return null;

        return new ValidString(value);
    }
}

這就是我想從StackFrame跳過整個課程的方式:

    foreach(StackFrame stackFrame in stackTrace.GetFrames())
        if (!stackFrame.GetClass().IsDefined(typeof(StackTraceHiddenAttribute), true))
            return stackFrame;

簡而言之:如何做這樣的事情?

bool markedWithSomeAttribute = stackTrace.GetFrame(i).GetClass().IsDefined(typeof(SomeAttribute), true);

在這里得到答案: https ://docs.microsoft.com/en-us/answers/questions/907789/how-to-check-if-class-attribute-defined-in-stackfr.html

解決方案:

bool marked = stackFrame.GetMethod().DeclaringType.CustomAttributes.Any(ca => ca.AttributeType == typeof(StackTraceHiddenAttribute));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM