c# - 获取没有名称的 MethodInfo 作为字符串

标签 c# linq

我正在从 LINQ 表达式构建 SQL 表达式并且非常喜欢它。但是,出现了重构问题。假设我想检查 MethodCallExpression 的方法,我会做这样的事情:

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

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

它工作得很好,但如果有人要重命名、移动或以某种方式改变方法,这将无提示地失败。

我想出了一个主意,但我觉得它很丑,因为...

if (expr.Method == new Func<string,string,bool>(SqlFilterExtensions.Like).Method)
{
    // Generate the SQL...
}

最佳答案

我不明白你在做什么,我想你可以完全避免你在这里展示的一些代码。

我写了这个“GetMemberName”扩展方法,你可能可以用这段代码做一些事情:

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);

编辑:

只是草拟一个解决方案:

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
}

关于c# - 获取没有名称的 MethodInfo 作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2379131/

相关文章:

c# - 绑定(bind) WPF 密码框

c# - 可拖动的 StackPanel Windows Phone 8.1

c# - MVC3 自定义 View 引擎

c# - 我应该何时打开和关闭与 SQL Server 的连接

c# - 使用 String.IsNullOrEmpty(string) 和 Nhibernate 创建动态 Linq 表达式

c# - 如何使用 Linq 和 ASP.Net Forms 在多个表之间编写联接

c# - Interlocked.Exchange<T> 是 Microsoft 的预期 Swap 方法吗?

c# - LinQtoExcel 使用 asp 文件上传

asp.net - 我应该在 2016 年为 .Net 使用哪个 ORM 来与 SQL 服务器通信?

entity-framework - EFCore 3.1 - 通过 Any 存在查询;查询无法翻译