比较两个表达式的结果 [英] Compare the Results of Two Expressions
本文介绍了比较两个表达式的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想比较两个表达式的结果,以确定它们是否相等.下面的代码可以编译,但是我得到一个例外,那就是参数数量不正确.考虑到这一点,我有两个问题.
I'd like to compare the results of two expressions to determine if they are equal. The below code compiles but I get an exception that there is an incorrect number of parameters. With that in mind I have two questions.
- 比较两个表达式的正确Lambda表达式方法是什么?
- 比较两个表达式的结果是否有更好/更简单的方法?
谢谢您的帮助.
瑞安
public static void SaveValue<T>(this Something first, ref Something second, Expression<Func<Something, T>> outExpr)
{
Expression.Lambda<Func<Something, Something, bool>>(
Expression.Equal(
Expression.Invoke(outExpr, Expression.Parameter(typeof(Something))),
Expression.Invoke(outExpr, Expression.Parameter(typeof(Something)))
)).Compile()(first, second);
}
public class Something
{
public Something() {}
public Something(string here) { Here = here; }
public Something(int there ) { There = there; }
public Something(string here, int there) { Here = here; There = there; }
public string Here { get; set; }
public int There { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
var mySomething = new Something("Hello");
var mySomething3 = new Something("World", 3);
mySomething3.SaveValue(ref mySomething, s => s.Here);
mySomething3.SaveValue(ref mySomething, s => s.There);
Console.WriteLine(mySomething3.Here + ", " + mySomething3.There);
Console.WriteLine(mySomething.Here + ", " + mySomething.There);
}
}
推荐答案
您好,Ryan Sof 软件,
根据您的描述和相关代码,我创建了一个演示,它引发了异常.需要在名为的方法上添加参数 表达式 . Lambda. 请像这样修改代码:
Based on your description and related code, I create a demo and it throws an exception. which need to add parameters on your method named Expression.Lambda. please modify the code like this:
public static void SaveValue<T>(this Something first, ref Something second, Expression<Func<Something, T>> outExpr)
{
ParameterExpression param1 = Expression.Parameter(typeof(Something));
ParameterExpression param2 = Expression.Parameter(typeof(Something));
var val1 = Expression.Invoke(outExpr, param1);
var val2 = Expression.Invoke(outExpr, param2);
var andExp = Expression.Equal(val1, val2);
Expression.Lambda<Func<Something, Something, bool>>(
andExp, param1, param2
).Compile()(first, second);
}
最诚挚的问候,
吴可乐
这篇关于比较两个表达式的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文