如何将 StartsWith() 作为参数传递给 Expression.Call()?

问题描述 投票:0回答:2

我正在尝试将 StartsWith() 函数作为表达式调用并将常量传递给它。

var textConstant =Expression.Constant(text);
var startsWith = Expression.Call(StartsWith ,textConstant); //something like this

我是 C# 的新手,我不知道如何将它们传递给 Expression.Call()。

c# .net-core c#-4.0 expression-trees
2个回答
0
投票

我不确定你想要什么,所以这里有两个我看到的选项:

  1. Expression.Call()
    函数只接受一个参数,而您想传递以 textConstant 作为参数的
    StartsWith()
    函数。这是该怎么做:

var textConstant =Expression.Constant(text);

var startsWith = Expression.Call(StartsWith(textConstant));

  1. Expression.Call()
    函数有两个参数,您想要传递不带参数的
    StartsWith()
    函数作为第一个参数,而
    textConstant
    作为另一个参数。如果是这样,您只需添加 () :

var textConstant =Expression.Constant(text);

var startsWith = Expression.Call(StartsWith(), textConstant);


0
投票

这里是样品:

 string text = "Some string";
 string startsText = "Some";
        
 Expression callExpr = Expression.Call(
                          Expression.Constant(text), 
                          typeof(String).GetMethod("StartsWith", 
                                         new Type[] { typeof(String) }),
                          Expression.Constant(startsText));
        
 // print the expression
 Console.WriteLine(callExpr);
        
 // execute the expression
 var lambda = Expression.Lambda<Func<bool>>(callExpr).Compile();
 Console.WriteLine(lambda());
© www.soinside.com 2019 - 2024. All rights reserved.