我正在尝试编写FXCop规则来验证以下类型的代码,
namespace ClassTarget
{
public class Class1
{
private static readonly Type DeclType = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
public void StartWatchingForUpdates1()
{
using (new TraceGuard(DeclType,"StartWatchingForUpdates1"))
{
Console.Write("Test");
}
}
/// <see cref="IAutomaticUpdaterBackendHelper.StopWatchingForUpdates"/>
public void StopWatchingForUpdates2()
{
using (new TraceGuard(DeclType, "StopWatchingForUpdates2"))
{
}
}
}
}
这里我要验证方法名称和TraceGuard构造函数内部调用的字符串(使用(新的TraceGuard(DeclType,&#34; StopWatchingForUpdates2&#34;))是否相同。
我可以从我的FX警察规则中捕获Traceguard构造函数,但无法找到传递给它的第二个参数作为方法名称。
有人可以帮我吗?
答案 0 :(得分:0)
感谢您的帮助,虽然这不是确切的解决方案,但它带我到了确切的一个。非常感谢!!
在下面找到我的代码,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.FxCop;
using Microsoft.FxCop.Sdk;
namespace MyCustomRule
{
public class MyCustomRule : BaseIntrospectionRule
{
private TypeNode m_ArgumentException;
string errorMessage, methodName;
Boolean problemyn;
public MyCustomRule() :
base("MyCustomRule", "MyCustomRule.Connection", typeof(MyCustomRule).Assembly)
{
}
public override ProblemCollection Check(Member member)
{
Method method = member as Method;
MetadataCollection<Instruction> enumerator = method.Instructions;
methodName = method.Name.ToString();
StatementCollection stmt = method.Body.Statements;
try
{
problemyn = false;
VisitStatements(stmt);
if (problemyn)
{
Resolution resolu = GetResolution(new string[] { method.ToString() + errorMessage });
Problems.Add(new Problem(resolu));
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
return Problems;
}
public override void VisitExpression(Expression expr)
{
Construct cnstruct;
InstanceInitializer instInit;
int i = 0;
cnstruct = expr as Construct;
if (cnstruct == null)
return;
instInit = (InstanceInitializer)((MemberBinding)cnstruct.Constructor).BoundMember;
foreach (Expression operand in cnstruct.Operands)
{
if (instInit.Parameters[i].Name.Name == "strMethodName")
{
Literal lit;
String litString;
lit = operand as Literal;
if (lit == null)
continue;
litString = lit.Value as String;
if (litString == null)
continue;
if (methodName == litString )
{
break;
}
else
{
problemyn = true;
errorMessage += methodName + " " + litString;
}
}
i++;
}
}
}
}