非字符串类型反射



给定以下代码…

public static class Simulate
{
    public static bool Boolean(bool b)
    {
        return b;
    }
}

我想检查表达式是否使用了这个静态函数。我想避免字符串类型的反射,以便使代码更易于重构,这就是为什么我尝试做以下类似的事情。我尝试了以下代码:

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)。但是是否有任何方法我只能得到布尔字符串?

您可以从表达式体访问MethodInfo,然后访问它的名称,它将返回一个字符串布尔值:

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

最新更新