给出以下代码..
public static class Simulate
{
public static bool Boolean(bool b)
{
return b;
}
}
我想检查Expression是否使用此静态函数。我想避免stringly-typed反射,以便使代码更具有重构友好性,这就是我尝试执行以下操作的原因,类似于this。我尝试了以下代码:
protected virtual Expression VisitMethodCall(MethodCallExpression m)
{
if (m.Method == Simulate.Boolean)
但这不起作用,所以我尝试了这个:
Expression<Action> fb = () => Simulate.Boolean(true);
string booleanName = fb.Body.ToString();
if (m.Method.DeclaringType == typeof(Simulate))
{
if (m.Method.Name == booleanName)
但是,预计上述代码会返回布尔值(true)。但有什么办法我只能得到布尔字符串?
答案 0 :(得分:2)
您可以从表达式的正文中访问MethodInfo
,然后访问它的名称,它将返回一个字符串 Boolean :
Expression<Action> fb = () => Simulate.Boolean(true);
var call = fb.Body as MethodCallExpression;
if (call != null)
Console.WriteLine (call.Method.Name); //prints "Boolean" as a string