i.Contai-6ren">
gpt4 book ai didi

c# - Linq表达式替换参数类型

转载 作者:太空宇宙 更新时间:2023-11-03 17:04:35 25 4
gpt4 key购买 nike

我有一个谓词,它是在提供所有扩展方法后由 lambda 表达式构成的。例如:

(new List<string>).Where(i => i.Contains("some")).Where(i => i.Contains("second_some"));

"List<>"只是示例,可能有我的自定义数据上下文或对象集合。所以,我有一个“Expression<...>”,它是基本类型“Expression”。

问题是,是否有任何代码可以遍历表达式树,并将参数类型(在我们的示例中为“字符串”)替换为指定的另一个类型?

我已经找到了如何替换参数类型,但是当“Where”扩展方法中某处的方法具有旧参数类型的签名时会发生冲突。

也许有人遇到了解决方案?谢谢。

最佳答案

表达式是不可变类型。要替换参数(及其类型),您需要使用原始表达式的主体创建一个新表达式,并传递您要使用的参数。

            var resultingIQueryable = ( new List<string> () ).AsQueryable<string>().Where (i => i.Contains ("some")).Where (i => i.Contains ("second_some"));

// the Queryable.Where is a MethodCallExpression
var expressionOriginal = resultingIQueryable.Expression as MethodCallExpression;
// there are multiple where calls, this makes it all a little bit more confusing.
// The linq tree is built 'backwards'
// the first parameter of the expression is a MethodCallExpression:
// {System.Collections.Generic.List`1[System.String].Where(i => i.Contains("some"))}
// the second parameter:
// {i => i.Contains("second_some")}
//
// disecting the first parameter you will again find 2 parameters:
// {System.Collections.Generic.List`1[System.String]}
// {i => i.Contains("some")}

使用 linq(方法)语法构建表达式然后遍历树构建新表达式并不是一个好的做法。如果我是你,我会尝试使用 Expression.Call & Expression.Lambda & Expression.Paremeter... 语法构建表达式。

关于c# - Linq表达式替换参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3195582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com