创建自定义 IEnumerable.Contains LINQ 表达式
我需要创建一个派生自 System.Linq.Expressions.Expression 的自定义“Contains”LINQ 表达式,该表达式在内部执行 IEnumerable.Contains 方法调用。该类将接受两个表达式参数。第一个计算结果为 IEnumerable 集合类型的实例,第二个计算结果为 T 类型的实例。
我需要将其作为其自己的类,因为我想重写 ToString 方法以返回表示正在执行的操作的自定义字符串。
到目前为止,我有以下问题:
public class ContainsExpression : Expression
{
public ContainsExpression(Expression left, Expression right) :
base(ExpressionType.Call, typeof(ContainsExpression))
{
Left = left;
Right = right;
// Error here: value cannot be null
Expression.Call(
typeof(IEnumerable).GetMethod("Contains", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public), left, right);
}
public static ContainsExpression Contains(Expression itemExpr, Expression collectionExpr)
{
return new ContainsExpression(itemExpr, collectionExpr);
}
public override string ToString()
{
return Left.ToString() + " Contains " + Right.ToString();
}
public Expression Left { get; private set; }
public Expression Right { get; private set; }
}
我在使用 Expression.Call 时遇到问题。基本上,我想调用 IEnumerable.Contains()。
任何指点总是值得赞赏。 TIA。
I need to create a custom "Contains" LINQ expression that derives from System.Linq.Expressions.Expression that internally performs an IEnumerable.Contains method call. This class will accept two expression parameters. The first evaluates to and instance of type IEnumerable collection and second evaluates to an instance of type T.
I need this to be its own class as i want to override the ToString method to return a custom string that represents the operation being performed.
So far, I have the following:
public class ContainsExpression : Expression
{
public ContainsExpression(Expression left, Expression right) :
base(ExpressionType.Call, typeof(ContainsExpression))
{
Left = left;
Right = right;
// Error here: value cannot be null
Expression.Call(
typeof(IEnumerable).GetMethod("Contains", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public), left, right);
}
public static ContainsExpression Contains(Expression itemExpr, Expression collectionExpr)
{
return new ContainsExpression(itemExpr, collectionExpr);
}
public override string ToString()
{
return Left.ToString() + " Contains " + Right.ToString();
}
public Expression Left { get; private set; }
public Expression Right { get; private set; }
}
I am having trouble with the Expression.Call. Basically, I want to invoke IEnumerable.Contains().
Any pointers is always appreciated. TIA.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,一个问题是
IEnumerable
接口没有Contains
方法。您可能正在寻找 System.Linq.Enumerable 中声明的扩展方法。尝试(假设您有一个
using System.Linq;
指令):Well, one problem is that the
IEnumerable
interface doesn't have aContains
method. You're probably looking for the extension-method declared inSystem.Linq.Enumerable
.Try (assuming you have a
using System.Linq;
directive):