Getting MethodInfo without a name as a string

I create SQL expressions from LINQ Expressions and really love it. However, there was a problem with refactoring. Suppose I want to test the MethodCallExpression method, 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 fine, but if someone had to rename, move, or somehow change the method, it will fail.

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

 if (expr.Method == new Func<string,string,bool>(SqlFilterExtensions.Like).Method) { // Generate the SQL... } 
+4
source share
3 answers

I don’t understand what you are doing, I think you could probably completely avoid the code that you are showing here.

I wrote this GetMemberName extension method, you can probably 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 outline the 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
source
  • This will not fail if you have unit tests for testing.
  • If you used ReSharper, he would suggest changing the text in the string literal at the same time as the method was renamed.
+1
source

If you have control over the Like method, perhaps you can work from there directly, rather than checking expressions later.

If you do not have control over the method, there is no other way than to do this by comparing the name

0
source

Source: https://habr.com/ru/post/1303115/


All Articles