質問

Given the following code..

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

}

I wanted to check if the Expression uses this static function. I wanted to avoid stringly-typed reflection, so as to make the code more refactoring-friendly, that's why I'm trying to do the following, similar to this. I tried the following code:

protected virtual Expression VisitMethodCall(MethodCallExpression m)
{

    if (m.Method == Simulate.Boolean)

But that doesn't work, so I tried this:

Expression<Action> fb = () => Simulate.Boolean(true);

string booleanName = fb.Body.ToString();

if (m.Method.DeclaringType == typeof(Simulate))
{
     if (m.Method.Name == booleanName)

However, expectedly, the above code returns Boolean(true). But is there any way I can only get the Boolean string?

役に立ちましたか?

解決

You can access MethodInfo from the body of the expression, and then access it's name and it will return a string 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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top