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

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

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

问题

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

  1. var textConstant = Expression.Constant(text);
  2. var startsWith = Expression.Call(StartsWith, 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.

  1. var textConstant =Expression.Constant(text);
  2. 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

这是示例:

  1. string text = "Some string";
  2. string startsText = "Some";
  3. Expression callExpr = Expression.Call(
  4. Expression.Constant(text),
  5. typeof(String).GetMethod("StartsWith",
  6. new Type[] { typeof(String) }),
  7. Expression.Constant(startsText));
  8. // 打印表达式
  9. Console.WriteLine(callExpr);
  10. // 执行表达式
  11. var lambda = Expression.Lambda<Func<bool>>(callExpr).Compile();
  12. Console.WriteLine(lambda());
英文:

Here is sample:

  1. string text = &quot;Some string&quot;;
  2. string startsText = &quot;Some&quot;;
  3. Expression callExpr = Expression.Call(
  4. Expression.Constant(text),
  5. typeof(String).GetMethod(&quot;StartsWith&quot;,
  6. new Type[] { typeof(String) }),
  7. Expression.Constant(startsText));
  8. // print the expression
  9. Console.WriteLine(callExpr);
  10. // execute the expression
  11. var lambda = Expression.Lambda&lt;Func&lt;bool&gt;&gt;(callExpr).Compile();
  12. Console.WriteLine(lambda());

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

发表评论

匿名网友

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

确定