我正在从 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/