开发者

Getting MethodInfo without name as string

开发者 https://www.devze.com 2022-12-22 01:59 出处:网络
I\'m building SQL expressions from LINQ Expressions and liking it verry much. However an issue with refactoring has come up. Suppose I want to check the Method of a MethodCallExpression, I would do so

I'm building SQL expressions from LINQ Expressions and liking it verry much. However an issue with refactoring has come up. Suppose I want to check the Method of a MethodCallExpression, I would do something like this:

MethodCallExpression expr = ...  // An expression from somewhere...

if (expr.Method == typeof(SqlFilterExtensions).GetMethod("Like", BindingFlags.Static | BindingFlags.Public))
{
    // Generate the SQL...
}

It works great, but if someone was to rename, move or somehow alter the method, this would fail silently.

I have come up with one idea, but I find it ugly as H...

i开发者_如何学Cf (expr.Method == new Func<string,string,bool>(SqlFilterExtensions.Like).Method)
{
    // Generate the SQL...
}


I don't understand what you are doing, I think you could probably completely avoid some of the code you show here.

I wrote this "GetMemberName" extension method, you probably can do something with this code:

public static string GetMemberName<T, TResult>(
    this T anyObject, 
    Expression<Func<T, TResult>> expression)
{
    return ((MemberExpression)expression.Body).Member.Name;
}

// call as extension method, if you have a instance
string lengthPropertyName = "abc".GetMemberName(x => x.Length);

// or call as a static method, by providing the type in the argument
string lengthPropertyName = ReflectionUtility.GetMemberName(
    (string x) => x.Length);

Edit:

just to sketch up a solution:

public static bool IsMethod<TResult>(
  MethodInfo method, 
  Expression<Func<TResult>> expression)
{
  // I think this doesn't work like this, evaluate static method call
  return method == ((MemberExpression)expression.Body).Member;
}

if (IsMethod(expr.Method, () => SqlFilterExtensions.Like))
{
  // generate SQL
}


  1. It wouldn't fail silently if you had unit tests to test it.
  2. If you used ReSharper, it would offer to change the text in the string literal at the same time as renaming the method.


If you have control over the Like method, maybe you could work from there directly instead of inspecting the expressions later.

If you don't have control over the method there is no other way than to do it by comparing the name

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号