简体   繁体   English

如何通过自定义规则检测FxCop中SPECIFIC方法的调用 - 在Check方法中放入什么

[英]How to detect calls to a SPECIFIC method in FxCop via a custom rule — what to put in Check method

I want to disallow calls to a specific method (MessageBox.Show) via a custom FxCop rule. 我想通过自定义FxCop规则禁止调用特定方法(MessageBox.Show)。 I know the mechanics of how to get an FxCop rule custom-implemented (the XML file, inheriting from BaseIntrospectionRule, etc.) My question here is what I put in the "Check" method. 我知道如何获得自定义实现的FxCop规则的机制(XML文件,继承自BaseIntrospectionRule等)我的问题是我在“检查”方法中提出的。

Below is the initial draft I have based on poking around a lot on the web, but I'm very puzzled as to what I would actually populate in the two fields marked with ????? 以下是我在网上大量探讨的初步草案,但我很困惑,我会在标有?????的两个字段中实际填充什么。 below. 下面。

I'm not sure even this solution, as it exists, would work. 我不确定即使这个解决方案存在也会起作用。 What is the fool-proof to make sure I'm doing what I want -- which is catching all calls to MessageBox.Show? 什么是傻瓜证明我正在做我想做的事 - 这是捕捉所有对MessageBox.Show的调用?

public override ProblemCollection Check(Member member)
{
    Method method = member as Method;
    if (method == null)
    {
        return null;
    }
    MetadataCollection<Instruction>.Enumerator enumerator = method.Instructions.GetEnumerator();
    while (enumerator.MoveNext())
    {
        Instruction current = enumerator.Current;
        switch (current.OpCode)
        {
            case OpCode.Call:
            case OpCode.Callvirt:
            {
                Method method3 = current.Value as Method;
                if (method3 == **?????**)
                {
                    Problem item = new Problem(base.GetResolution(**?????**), current);
                    base.Problems.Add(item);
                }
                break;
            }
        }
    }
    return base.Problems;
}

You might want to take a look at how the built-in SpecifyMessageBoxOptions rule is built using a decompiler like Reflector. 您可能想看看如何使用像Reflector这样的反编译器构建内置的SpecifyMessageBoxOptions规则。 There are other possible approaches, but name comparison is usually fine unless you have reason to believe that it will cause excessive false positives. 还有其他可能的方法,但名称比较通常很好,除非你有理由相信它会导致过多的误报。

How about something like this? 这样的事怎么样?

   public override ProblemCollection Check(Member member)
    {
        Method method = member as Method;
        if (method != null) 
        {
            this.Visit(method.Body);
        }
        return this.Problems;
    }

    public override void VisitMethodCall(MethodCall call)
    {
        base.VisitMethodCall(call);
        Method targetMethod = (Method)((MemberBinding)call.Callee).BoundMember;
        if (targetMethod.Name.Name.Contains("MessageBox.Show"))
           this.Problems.Add(new Problem(this.GetResolution(), call));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM