/IronPython_Main/Runtime/Samples/ExpressionTree/UESamples/ConsoleApplication1/CIfThen.cs

# · C# · 54 lines · 38 code · 8 blank · 8 comment · 0 complexity · b768202558d5c05c104bbbe9439196f0 MD5 · raw file

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Microsoft.Scripting.Ast;
  5. namespace Samples {
  6. class CIfThen {
  7. //Expression.IfThen(MethodInfo, Expression[])
  8. static public void IfThen1() {
  9. //<Snippet1>
  10. // add the following directive to your file
  11. // using Microsoft.Scripting.Ast;
  12. //We'll define a helper lambda to print out some information
  13. ParameterExpression Text = Expression.Parameter(typeof(string));
  14. var MyPrint = Expression.Lambda<Action<string>>(
  15. Expression.Call(
  16. null,
  17. typeof(Console).GetMethod("WriteLine",new Type[]{typeof(string)}),
  18. Text
  19. ),
  20. Text
  21. );
  22. //This element defines an IfThen expression.
  23. Expression MyIfThen1 = Expression.IfThen(
  24. Expression.Constant(true),
  25. Expression.Invoke(
  26. MyPrint,
  27. Expression.Constant("Ran 1")
  28. )
  29. );
  30. Expression MyIfThen2 = Expression.IfThen(
  31. Expression.Constant(false),
  32. Expression.Invoke(
  33. MyPrint,
  34. Expression.Constant("Ran 2")
  35. )
  36. );
  37. var MyBlock = Expression.Block(
  38. MyIfThen1,
  39. MyIfThen2
  40. );
  41. //The end result should be "Ran 1".
  42. Expression.Lambda<Action>(MyBlock).Compile().Invoke();
  43. //</Snippet1>
  44. }
  45. }
  46. }