求可获取含单参数MessageBox.Show()调用的NDepend CQLinq查询
NDepend CQLinq查询:获取调用MessageBox.Show()的方法及参数数
需求
编写CQLinq查询,返回包含MessageBox.Show()调用的方法名称,以及对应Show()调用的参数数量(例如MessageBox.Show("Hullo")的参数数为1)。
原尝试代码及报错
原查询代码
from m in JustMyCode.Methods let showMethods = m.MethodsCalled.Where(m1 => m1.SimpleName == "Show" && m1.NbParameters > 0) where showMethods.Count() > 0 select new { Method=m, ShowCount=showMethods.Count(), ShowParameterCount = showMethods.Select(m1 => new { PCount= m1.NbParameters})}
报错信息
Type {IEnumerable
1<Record1>} not accepted to type a result argument.
Only IMethod, IField, IType, INamespace, IAssembly, IMember, ICodeElement, ICodeElementParent, ICodeContainer, IIssue and IRule enumerable of one of these types, string, bool, numerics, nullable of bool and numerics, IAbsoluteFilePath and IAbsoluteDirectoryPath are accepted.
错误原因
NDepend的CQLinq查询结果不支持返回集合类型的匿名对象,原代码中ShowParameterCount返回的是IEnumerable<匿名类型>,不符合结果类型要求。
解决方案
根据需求,提供两种可行的查询方案:
方案1:每个Show()调用单独输出
此方案会把每个MessageBox.Show()调用作为一条结果,清晰展示所属方法和该调用的参数数:
from m in JustMyCode.Methods from showCall in m.MethodsCalled where showCall.SimpleName == "Show" && showCall.ParentType.FullName == "System.Windows.Forms.MessageBox" // 精确匹配MessageBox类型,避免同名方法 select new { 调用方法 = m.FullName, Show调用参数数 = showCall.NbParameters }
方案2:按方法聚合展示
此方案会把同一个方法内的所有Show()调用参数数合并为字符串,同时显示调用次数:
from m in JustMyCode.Methods let showCalls = m.MethodsCalled.Where(c => c.SimpleName == "Show" && c.ParentType.FullName == "System.Windows.Forms.MessageBox") where showCalls.Any() select new { 方法名称 = m.FullName, Show调用次数 = showCalls.Count(), 各调用参数数 = string.Join(", ", showCalls.Select(c => c.NbParameters)) }
说明
- 加入
showCall.ParentType.FullName == "System.Windows.Forms.MessageBox"是为了精确匹配MessageBox类的Show方法,避免误匹配其他类中同名的Show方法。 - 方案1适合查看每个调用的细节,方案2适合快速汇总每个方法的调用情况。
内容的提问来源于stack exchange,提问作者Peter M.
相关产品推荐
相关产品推荐

