【发布时间】:2025-12-21 04:40:11
【问题描述】:
我想编写一个规则,如果在由标记有特定属性的方法调用的任何方法中进行对象分配,该规则将失败。
到目前为止,我已经完成了这项工作,通过迭代所有调用我的方法的方法来检查使用CallGraph.CallersFor(),以查看是否有任何父方法具有该属性。
这适用于检查与要检查的方法相同的程序集中的父方法,但是在线阅读时,似乎有一次CallGraph.CallersFor() 确实查看了所有程序集,但现在没有。
问题:有没有办法获取调用给定方法的方法列表,包括不同程序集中的方法?
替代答案:如果上述方法不可行,我如何遍历给定方法调用的每个方法,包括不同程序集中的方法。
示例:
-----In Assembly A
public class ClassA
{
public MethodA()
{
MethodB();
}
public MethodB()
{
object o = new object(); // Allocation i want to break the rule
// Currently my rule walks up the call tree,
// checking for a calling method with the NoAllocationsAllowed attribute.
// Problem is, because of the different assemblies,
// it can't go from ClassA.MethodA to ClassB.MethodB.
}
}
----In Assembly B
public var ClassAInstance = new ClassA();
public class ClassB
{
[NoAllocationsAllowed] // Attribute that kicks off the rule-checking.
public MethodA()
{
MethodB();
}
public MethodB()
{
ClassAInstance.MethodA();
}
}
我真的不介意规则在哪里报告错误,在这个阶段得到错误就足够了。
【问题讨论】:
-
我不确定我是否真的了解您要验证的内容。您能否提供一个应该生成规则违规的代码的具体示例?
标签: c# .net fxcop call-graph