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

huangapple go评论67阅读模式
英文:

How to pass StartsWith() as a parameter to Expression.Call()?

问题

I'm trying to call StartsWith() function as an expression and pass a constant to it.

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

I'm new to C# and I couldn't figure out how to pass these into Expression.Call().

英文:

Im trying to call StartsWith() function as an expression and pass a constant to it.

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

Im new to c# and I couldn't figure out how to pass these into Expression.Call().

答案1

得分: -1

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));

// 打印表达式
Console.WriteLine(callExpr);

// 执行表达式
var lambda = Expression.Lambda<Func>(callExpr).Compile();
Console.WriteLine(lambda());

英文:

Here is sample:

 string text = &quot;Some string&quot;;
 string startsText = &quot;Some&quot;;
		
 Expression callExpr = Expression.Call(
                          Expression.Constant(text), 
                          typeof(String).GetMethod(&quot;StartsWith&quot;, 
                                         new Type[] { typeof(String) }),
                          Expression.Constant(startsText));
		
 // print the expression
 Console.WriteLine(callExpr);
		
 // execute the expression
 var lambda = Expression.Lambda&lt;Func&lt;bool&gt;&gt;(callExpr).Compile();
 Console.WriteLine(lambda());

huangapple
  • 本文由 发表于 2023年3月21日 01:46:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75793622.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定