Domanda

I have created an FxCop rule that checks for DateTime.Now use. It works pretty well, except that it reports the offending line number as the start of the method, rather than the line of code that actually calls DateTime.Now. What do I need to do to get the right line number in the FxCop report. Here's my code:

public override void VisitMemberBinding(MemberBinding memberBinding)
{
   string name = memberBinding.BoundMember.FullName;
   if (name == "System.DateTime.get_Now")
   {
      Problems.Add(new Problem(GetResolution(), memberBinding.BoundMember.SourceContext));
   }

   base.VisitMemberBinding(memberBinding);
}

I've tried memberBinding.SourceContext and memberBinding.BoundMember.SourceContext and both return the method's start line number.

I could use SourceContext.(Start|End)LineNumber but which one? Seems that I am just not using the correct object.SourceContext

È stato utile?

Soluzione

The core problem is that the FxCop analysis engine does not assign a source context to a member binding. It does, however, assign a source context to a method call, so you could replace your VisitMemberBinding override with the following VisitMethodCall override:

public override void VisitMethodCall(MethodCall call)
{
    string name = ((MemberBinding)call.Callee).BoundMember.FullName;
    if (name == "System.DateTime.get_Now")
    {
        this.Problems.Add(new Problem(this.GetResolution(), call));
    }

    base.VisitMethodCall(call);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top