C#中如何检查StackFrame对应类是否定义了指定特性?
实现方法
StackFrame类型本身没有提供GetClass()方法,要判断栈帧所属类是否标记了指定特性,需要通过栈帧对应方法的DeclaringType属性获取方法所属的类型,再执行特性检查即可。
完整过滤逻辑
修改原来的栈帧遍历代码,同时判断方法级、类级的StackTraceHidden标记,兼容空值场景:
foreach(StackFrame stackFrame in stackTrace.GetFrames()) { MethodBase method = stackFrame.GetMethod(); // 跳过无法解析方法的栈帧 if (method == null) continue; // 检查方法本身是否标记特性 bool methodMarked = method.IsDefined(typeof(StackTraceHiddenAttribute), true); // 检查方法所属类是否标记特性,处理无所属类的全局方法/动态方法场景 bool typeMarked = method.DeclaringType?.IsDefined(typeof(StackTraceHiddenAttribute), true) ?? false; if (!methodMarked && !typeMarked) { return stackFrame; } }
适配嵌套类场景(可选)
如果待跳过类存在嵌套类,需要嵌套类自动继承外层类的隐藏标记,可以加个类型链遍历方法,向上查找所有外层类的特性:
private static bool IsHiddenByTypeChain(Type targetType) { Type currentType = targetType; while (currentType != null) { if (currentType.IsDefined(typeof(StackTraceHiddenAttribute), true)) { return true; } currentType = currentType.DeclaringType; } return false; }
把之前类级判断的逻辑替换为bool typeMarked = method.DeclaringType != null && IsHiddenByTypeChain(method.DeclaringType);即可。
说明
- 该方案对构造函数、私有方法、隐式/显式转换运算符、静态方法都生效,类级标记
[StackTraceHidden]的类型下所有方法对应的栈帧都会被正确过滤,不需要逐个给方法加特性。 DeclaringType取到的是方法实际定义的类型,不会因为子类继承父类方法出现判断偏差。
内容的提问来源于stack exchange,提问作者Yoro
相关产品推荐
相关产品推荐

