表达式树 System.Linq.Expressions

一.Expressions命名空间里的类以及作用

1.BinaryExpression

表示具有二进制运算符的表达式
注解:下表汇总了工厂方法,这些方法可用于创建 BinaryExpression 具有特定节点类型(由属性表示)的工厂方法 NodeType 。 每个表都包含特定操作类的信息,如算术或按位运算。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
此外, MakeBinary 还可以使用这些方法来创建 BinaryExpression 。 这些工厂方法可用于创建 BinaryExpression 表示二元运算的任何节点类型的。 类型为的这些方法的参数指定所 NodeType 需的节点类型。
示例
下面的示例创建一个 BinaryExpression 对象,该对象表示一个数与另一个数之和。

// Create a BinaryExpression that represents subtracting 14 from 53.
System.Linq.Expressions.BinaryExpression binaryExpression =
    System.Linq.Expressions.Expression.MakeBinary(
        System.Linq.Expressions.ExpressionType.Subtract,
        System.Linq.Expressions.Expression.Constant(53),
        System.Linq.Expressions.Expression.Constant(14));

Console.WriteLine(binaryExpression.ToString());

// 输出结果:
//
// (53 - 14)
2.BlockExpression

表示包含一个表达式序列的块,表达式中可定义变量
注解:Block方法可用于创建 BlockExpression 。

//  block expression 允许连续的执行多个表达式
//  当 block expression 被执行,
// 它返回的序列是最后一个表达式的值
BlockExpression blockExpr = Expression.Block(
    Expression.Call(
        null,
        typeof(Console).GetMethod("Write", new Type[] { typeof(String) }),
        Expression.Constant("Hello ")
       ),
    Expression.Call(
        null,
        typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),
        Expression.Constant("World!")
        ),
    Expression.Constant(42)
);

Console.WriteLine("执行表达式树的结果:");
// 下面的语句首先创建一个表达式树,
// 然后编译,执行。
var result = Expression.Lambda<Func<int>>(blockExpr).Compile()();

// 输出表达式
Console.WriteLine("输出表达式:");
foreach (var expr in blockExpr.Expressions)
    Console.WriteLine(expr.ToString());

// 打印出表达式树执行的结果。
Console.WriteLine("输出结果:");
Console.WriteLine(result);

// This code example produces the following output:
//
// 执行表达式树的结果:
// Hello World!

// 输出表达式:
// Write("Hello ")
// WriteLine("World!")
// 42

// 输出结果:
// 42
3.CatchBlock

表示 try 块中的 catch 语句。
注解:Catch方法可用于创建 CatchBlock 。

属性作用
body获取catch块的主体
Filter获取 CatchBlock 筛选器的主体。
Test获取此处理程序捕捉的 Exception 的类型
Variable获取对此处理程序捕捉的 Exception 对象的引用
 public static void Main(string[] args)
        {
            TryExpression tryCatchExpr = Expression.TryCatch(
                    Expression.Block(
                        Expression.Throw(Expression.Constant(new DivideByZeroException())),
                        Expression.Constant("Try block")
                    ),
                    Expression.Catch(
                        typeof(DivideByZeroException),
                        Expression.Constant("Catch block")
                    )
                );
            var func = Expression.Lambda<Func<string>>(tryCatchExpr).Compile();
            //输出 Catch block
            Console.WriteLine(func());
        }
4.ConditionalExpression

表示具有条件运算符的表达式。
注解:使用 Condition 工厂方法来创建 ConditionalExpression 。的 NodeType ConditionalExpression 为 Conditional 。



int num = 100;


Expression conditionExpr = Expression.Condition(
                           Expression.Constant(num > 10),
                           Expression.Constant("num is greater than 10"),
                           Expression.Constant("num is smaller than 10")
                         );

// Print out the expression.
Console.WriteLine(conditionExpr.ToString());

// The following statement first creates an expression tree,
// then compiles it, and then executes it.
Console.WriteLine(Expression.Lambda<Func<string>>(conditionExpr).Compile()());
// 输出结果:
//
// IIF("True", "num is greater than 10", "num is smaller than 10")
// num is greater than 10
5.ConstantExpression

表示具有常数值的表达式
注解:使用 Constant 工厂方法来创建 ConstantExpression 。的 NodeType ConstantExpression 为 Constant 。

Expression constantExpr = Expression.Constant(5.5);
// Print out the expression.
Console.WriteLine(constantExpr.ToString());
// You can also use variables.
double num = 3.5;
constantExpr = Expression.Constant(num);
Console.WriteLine(constantExpr.ToString());
// 输出结果:
//
// 5.5
// 3.5
6.DebugInfoExpression

发出或清除调试信息的序列点。 这使调试器能够在调试时突出显示正确的源代码

7.DefaultExpression

表示一个类型或空表达式的默认值。

Expression defaultExpr = Expression.Default(
                            typeof(byte)
                        );

Console.WriteLine(defaultExpr.ToString());

// The following statement first creates an expression tree,
// then compiles it, and then executes it.
Console.WriteLine(
    Expression.Lambda<Func<byte>>(defaultExpr).Compile()());

// 输出结果:
//
// default(Byte)
// 0
8.DynamicExpression

表示一个动态操作。

9.DynamicExpressionVisitor

表示动态表达式树的访问者或重写者。
此类旨在通过继承来创建更专业化的类,其功能需要遍历、检查或复制动态表达式树

10.ElementInit

表示 IEnumerable 集合的单个元素的初始值设定项

string tree = "maple";

System.Reflection.MethodInfo addMethod = typeof(Dictionary<int, string>).GetMethod("Add");
// 创建一个表示调用的ElementInit
// Dictionary<int, string>.Add(tree.Length, tree).
System.Linq.Expressions.ElementInit elementInit =
    System.Linq.Expressions.Expression.ElementInit(
        addMethod,
        System.Linq.Expressions.Expression.Constant(tree.Length),
        System.Linq.Expressions.Expression.Constant(tree));

Console.WriteLine(elementInit.ToString());
// 输出:
//
// Void Add(Int32, System.String)(5,"maple")
11.Expression

提供一种基类,表示表达式树节点的类派生自该基类。 它还包含用来创建各种节点类型的 static(在 Visual Basic 中为 Shared)工厂方法。 这是一个 abstract 类。
方法描述地址



// Block Expression 连续执行多个表达式
// 执行时
// 返回最后一个值
BlockExpression blockExpr = Expression.Block(
    Expression.Call(
        null,
        typeof(Console).GetMethod("Write", new Type[] { typeof(String) }),
        Expression.Constant("Hello ")
       ),
    Expression.Call(
        null,
        typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),
        Expression.Constant("World!")
        ),
    Expression.Constant(42)
);

Console.WriteLine("The result of executing the expression tree:");
//下面的语句首先创建一个表达式树,
//编译,然后执行
var result = Expression.Lambda<Func<int>>(blockExpr).Compile()();

//从Block Expression 中输出表达式。
Console.WriteLine("The expressions from the block expression:");
foreach (var expr in blockExpr.Expressions)
    Console.WriteLine(expr.ToString());

//打印执行的结果.
Console.WriteLine("The return value of the block expression:");
Console.WriteLine(result);

// This code example produces the following output:
//
// The result of executing the expression tree:
// Hello World!

// The expressions from the block expression:
// Write("Hello ")
// WriteLine("World!")
// 42

// The return value of the block expression:
// 42

常用方法
常用方法

12. Expression

将强类型化的 Lambda 表达式表示为表达式树形式的数据结构。 此类不能被继承。
在这里插入图片描述

// Lambda expression as executable code.
Func<int, bool> deleg = i => i < 5;
// Invoke the delegate and display the output.
Console.WriteLine("deleg(4) = {0}", deleg(4));

// Lambda expression as data in the form of an expression tree.
System.Linq.Expressions.Expression<Func<int, bool>> expr = i => i < 5;
// Compile the expression tree into executable code.
Func<int, bool> deleg2 = expr.Compile();
// Invoke the method and print the output.
Console.WriteLine("deleg2(4) = {0}", deleg2(4));

/*  执行结果:

    deleg(4) = True
    deleg2(4) = True
*/
13.ExpressionVisitor

表示表达式树的访问者或重写者。详情地址
注解:此类旨在通过继承来创建更专业化的类,其功能需要遍历、检查或复制表达式树。
部分截图,方法功能

14.GotoExpression

表示无条件跳转。 这包括返回语句,break 和 continue 语句以及其他跳转。

// Add the following directive to your file:
// using System.Linq.Expressions;

// void类型的label expression,它是GotoExpression的目标。
LabelTarget returnTarget = Expression.Label();

// This block contains a GotoExpression.
// It transfers execution to a label expression that is initialized with the same LabelTarget as the GotoExpression.
// The types of the GotoExpression, label expression, and LabelTarget must match.
BlockExpression blockExpr =
    Expression.Block(
        Expression.Call(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }), Expression.Constant("GoTo")),
        Expression.Goto(returnTarget),
        Expression.Call(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }), Expression.Constant("Other Work")),
        Expression.Label(returnTarget)
    );

// The following statement first creates an expression tree,
// then compiles it, and then runs it.
Expression.Lambda<Action>(blockExpr).Compile()();

// 执行结果:
//
// GoTo

// "Other Work" 没有被打印原因
// GoTo expression 从expression .GoTo(returnTarget)传递执行
// 到 Expression.Label(returnTarget).
15.IndexExpression

表示对一个属性或数组进行索引



// 创建array数组
ParameterExpression arrayExpr = Expression.Parameter(typeof(int[]), "Array");

// array索引
ParameterExpression indexExpr = Expression.Parameter(typeof(int), "Index");

// This parameter represents the value that will be added to a corresponding array element.
ParameterExpression valueExpr = Expression.Parameter(typeof(int), "Value");

// This expression represents an array access operation.
// It can be used for assigning to, or reading from, an array element.
Expression arrayAccessExpr = Expression.ArrayAccess(
    arrayExpr,
    indexExpr
);

// This lambda expression assigns a value provided to it to a specified array element.
// The array, the index of the array element, and the value to be added to the element
// are parameters of the lambda expression.
Expression<Func<int[], int, int, int>> lambdaExpr = Expression.Lambda<Func<int[], int, int, int>>(
    Expression.Assign(arrayAccessExpr, Expression.Add(arrayAccessExpr, valueExpr)),
    arrayExpr,
    indexExpr,
    valueExpr
);

// Print out expressions.
Console.WriteLine("Array Access Expression:");
Console.WriteLine(arrayAccessExpr.ToString());

Console.WriteLine("Lambda Expression:");
Console.WriteLine(lambdaExpr.ToString());

Console.WriteLine("The result of executing the lambda expression:");

// The following statement first creates an expression tree,
// then compiles it, and then executes it.
// Parameters passed to the Invoke method are passed to the lambda expression.
Console.WriteLine(lambdaExpr.Compile().Invoke(new int[] { 10, 20, 30 }, 0, 5));

// 结果:
//
// Array Access Expression:
// Array[Index]

// Lambda Expression:
// (Array, Index, Value) => (Array[Index] = (Array[Index] + Value))

// The result of executing the lambda expression:
// 15
16.InvocationExpression

表示一个将委托或 Lambda 表达式应用到一个自变量表达式列表的表达式。
注解:使用 Invoke 工厂方法来创建 InvocationExpression 。NodeType的 InvocationExpression 为 Invoke 。

System.Linq.Expressions.Expression<Func<int, int, bool>> largeSumTest =
    (num1, num2) => (num1 + num2) > 1000;

// Create an InvocationExpression that represents applying
// the arguments '539' and '281' to the lambda expression 'largeSumTest'.
System.Linq.Expressions.InvocationExpression invocationExpression =
    System.Linq.Expressions.Expression.Invoke(
        largeSumTest,
        System.Linq.Expressions.Expression.Constant(539),
        System.Linq.Expressions.Expression.Constant(281));

Console.WriteLine(invocationExpression.ToString());

// This code produces the following output:
//
// Invoke((num1, num2) => ((num1 + num2) > 1000),539,281)
17.LabelExpression

表示一个标签,可以将该标签放置在任何 Expression 上下文中。 如果已跳转到该标签,则它将获取由对应的 GotoExpression 提供的值。 否则,它接收 DefaultValue 中的值。 如果 Type 等于 System.Void,则不应提供值。

18. LabelTarget

用于表示 GotoExpression 的目标。

// Add the following directive to the file:
// using System.Linq.Expressions;

// A label expression of the void type that is the target for Expression.Return().
LabelTarget returnTarget = Expression.Label();

// This block contains a GotoExpression that represents a return statement with no value.
// It transfers execution to a label expression that is initialized with the same LabelTarget as the GotoExpression.
// The types of the GotoExpression, label expression, and LabelTarget must match.
BlockExpression blockExpr =
    Expression.Block(
        Expression.Call(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }), Expression.Constant("Return")),
        Expression.Return(returnTarget),
        Expression.Call(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }), Expression.Constant("Other Work")),
        Expression.Label(returnTarget)
    );

// The following statement first creates an expression tree,
// then compiles it, and then runs it.
Expression.Lambda<Action>(blockExpr).Compile()();

// This code example produces the following output:
//
// Return

// "Other Work" is not printed because
// the Return expression transfers execution from Expression.Return(returnTarget)
// to Expression.Label(returnTarget).
19.LambdaExpression

介绍 lambda 表达式。 它捕获一个类似于 .NET 方法主体的代码块。
注解:LambdaExpression类型表示表达式树形式的 lambda 表达式。 Expression派生自和的类型 LambdaExpression 更明确地捕获 lambda 表达式的类型,也可用于表示 lambda 表达式。 在运行时,表示 lambda 表达式的表达式树节点始终为类型 Expression 。的属性的值 NodeType LambdaExpression 为 Lambda 。使用 Lambda 工厂方法创建 LambdaExpression 对象。

// Add the following directive to your file:
// using System.Linq.Expressions;

// A parameter for the lambda expression.
ParameterExpression paramExpr = Expression.Parameter(typeof(int), "arg");

// This expression represents a lambda expression
// that adds 1 to the parameter value.
LambdaExpression lambdaExpr = Expression.Lambda(
    Expression.Add(
        paramExpr,
        Expression.Constant(1)
    ),
    new List<ParameterExpression>() { paramExpr }
);

// Print out the expression.
Console.WriteLine(lambdaExpr);

// Compile and run the lamda expression.
// The value of the parameter is 1.
Console.WriteLine(lambdaExpr.Compile().DynamicInvoke(1));

// This code example produces the following output:
//
// arg => (arg +1)
// 2
20.ListInitExpression

表示具有集合初始值设定项的构造函数调用。
注解:使用 ListInit 工厂方法来创建 ListInitExpression 。的属性的值 NodeType ListInitExpression 为 ListInit 。

string tree1 = "maple";
string tree2 = "oak";

System.Reflection.MethodInfo addMethod = typeof(Dictionary<int, string>).GetMethod("Add");

// Create two ElementInit objects that represent the
// two key-value pairs to add to the Dictionary.
System.Linq.Expressions.ElementInit elementInit1 =
    System.Linq.Expressions.Expression.ElementInit(
        addMethod,
        System.Linq.Expressions.Expression.Constant(tree1.Length),
        System.Linq.Expressions.Expression.Constant(tree1));
System.Linq.Expressions.ElementInit elementInit2 =
    System.Linq.Expressions.Expression.ElementInit(
        addMethod,
        System.Linq.Expressions.Expression.Constant(tree2.Length),
        System.Linq.Expressions.Expression.Constant(tree2));

// Create a NewExpression that represents constructing
// a new instance of Dictionary<int, string>.
System.Linq.Expressions.NewExpression newDictionaryExpression =
    System.Linq.Expressions.Expression.New(typeof(Dictionary<int, string>));

// Create a ListInitExpression that represents initializing
// a new Dictionary<> instance with two key-value pairs.
System.Linq.Expressions.ListInitExpression listInitExpression =
    System.Linq.Expressions.Expression.ListInit(
        newDictionaryExpression,
        elementInit1,
        elementInit2);

Console.WriteLine(listInitExpression.ToString());

// This code produces the following output:
//
// new Dictionary`2() {Void Add(Int32, System.String)(5,"maple"),
// Void Add(Int32, System.String)(3,"oak")}
21.LoopExpression

表示无限循环。 可通过“中断”退出该循环。

// Add the following directive to the file:
// using System.Linq.Expressions;

// Creating a parameter expression.
ParameterExpression value = Expression.Parameter(typeof(int), "value");

// Creating an expression to hold a local variable.
ParameterExpression result = Expression.Parameter(typeof(int), "result");

// Creating a label to jump to from a loop.
LabelTarget label = Expression.Label(typeof(int));

// Creating a method body.
BlockExpression block = Expression.Block(
    new[] { result },
    Expression.Assign(result, Expression.Constant(1)),
        Expression.Loop(
           Expression.IfThenElse(
               Expression.GreaterThan(value, Expression.Constant(1)),
               Expression.MultiplyAssign(result,
                   Expression.PostDecrementAssign(value)),
               Expression.Break(label, result)
           ),
       label
    )
);

// Compile and run an expression tree.
int factorial = Expression.Lambda<Func<int, int>>(block, value).Compile()(5);

Console.WriteLine(factorial);

// This code example produces the following output:
//
// 120
22.MemberBinding

提供表示绑定的类派生自的基类,这些绑定用于对新创建对象的成员进行初始化(已过时)

23.MemberExpression

表示访问字段或属性
注解 :使用 Field 、 Property 或 PropertyOrField 工厂方法来创建 MemberExpression 。
的属性的值 NodeType MemberExpression 为 MemberAccess 。

class Animal
{
    public string species;
}

public static void CreateFieldExpression()
{
    Animal horse = new Animal();

    // Create a MemberExpression that represents getting
    // the value of the 'species' field of class 'Animal'.
    System.Linq.Expressions.MemberExpression memberExpression =
        System.Linq.Expressions.Expression.Field(
            System.Linq.Expressions.Expression.Constant(horse),
            "species");

    Console.WriteLine(memberExpression.ToString());

    // This code produces the following output:
    //
    // value(CodeSnippets.FieldExample+Animal).species
}
24.MemberInitExpression

表示调用构造函数并初始化新对象的一个或多个成员
注解:使用 MemberInit 工厂方法来创建 MemberInitExpression 。的属性的值 NodeType MemberInitExpression 为 MemberInit 。

class Animal
{
    public string Species {get; set;}
    public int Age {get; set;}
}

public static void CreateMemberInitExpression()
{
    System.Linq.Expressions.NewExpression newAnimal =
        System.Linq.Expressions.Expression.New(typeof(Animal));

    System.Reflection.MemberInfo speciesMember =
        typeof(Animal).GetMember("Species")[0];
    System.Reflection.MemberInfo ageMember =
        typeof(Animal).GetMember("Age")[0];

    // Create a MemberBinding object for each member
    // that you want to initialize.
    System.Linq.Expressions.MemberBinding speciesMemberBinding =
        System.Linq.Expressions.Expression.Bind(
            speciesMember,
            System.Linq.Expressions.Expression.Constant("horse"));
    System.Linq.Expressions.MemberBinding ageMemberBinding =
        System.Linq.Expressions.Expression.Bind(
            ageMember,
            System.Linq.Expressions.Expression.Constant(12));

    // Create a MemberInitExpression that represents initializing
    // two members of the 'Animal' class.
    System.Linq.Expressions.MemberInitExpression memberInitExpression =
        System.Linq.Expressions.Expression.MemberInit(
            newAnimal,
            speciesMemberBinding,
            ageMemberBinding);

    Console.WriteLine(memberInitExpression.ToString());

    // This code produces the following output:
    //
    // new Animal() {Species = "horse", Age = 12}
}
25.MemberListBinding

表示初始化新创建对象的一个集合成员的元素。
注解:使用 ListBind 工厂方法来创建 MemberListBinding 。的 MemberListBinding BindingType 属性等于 ListBinding 。

26.MemberMemberBinding

表示初始化新创建对象的一个成员的成员。
使用 MemberBind 工厂方法来创建 MemberMemberBinding 。对象的属性值 BindingType MemberMemberBinding 为 MemberBinding 。

27.MethodCallExpression

表示对静态方法或实例方法的调用。
使用 Call 、 ArrayIndex 或 ArrayIndex 工厂方法来创建 MethodCallExpression 。对象的属性值 NodeType MethodCallExpression 为 Call 。

string[,] gradeArray =
    { {"chemistry", "history", "mathematics"}, {"78", "61", "82"} };

System.Linq.Expressions.Expression arrayExpression =
    System.Linq.Expressions.Expression.Constant(gradeArray);

// Create a MethodCallExpression that represents indexing
// into the two-dimensional array 'gradeArray' at (0, 2).
// Executing the expression would return "mathematics".
System.Linq.Expressions.MethodCallExpression methodCallExpression =
    System.Linq.Expressions.Expression.ArrayIndex(
        arrayExpression,
        System.Linq.Expressions.Expression.Constant(0),
        System.Linq.Expressions.Expression.Constant(2));

Console.WriteLine(methodCallExpression.ToString());

// This code produces the following output:
//
// value(System.String[,]).Get(0, 2)
28.NewArrayExpression

表示创建一个新数组,并可能初始化该新数组的元素。
注解
下表显示了不同的工厂方法,你可以根据需要使用这些方法来创建 NewArrayExpression NodeType 。

NodeType工厂方法
NewArrayBoundsNewArrayBounds
NewArrayInitNewArrayInit

**(1)**下面的示例创建一个 NewArrayExpression 对象,该对象表示创建和初始化字符串的一维数组。

List<System.Linq.Expressions.Expression> trees =
    new List<System.Linq.Expressions.Expression>()
        { System.Linq.Expressions.Expression.Constant("oak"),
          System.Linq.Expressions.Expression.Constant("fir"),
          System.Linq.Expressions.Expression.Constant("spruce"),
          System.Linq.Expressions.Expression.Constant("alder") };

// Create an expression tree that represents creating and
// initializing a one-dimensional array of type string.
System.Linq.Expressions.NewArrayExpression newArrayExpression =
    System.Linq.Expressions.Expression.NewArrayInit(typeof(string), trees);

// Output the string representation of the Expression.
Console.WriteLine(newArrayExpression.ToString());

// This code produces the following output:
//
// new [] {"oak", "fir", "spruce", "alder"}

**(2)**下一个示例创建一个 NewArrayExpression 表示创建一维字符串数组的对象。

// Create an expression tree that represents creating a
// two-dimensional array of type string with bounds [3,2].
System.Linq.Expressions.NewArrayExpression newArrayExpression =
    System.Linq.Expressions.Expression.NewArrayBounds(
            typeof(string),
            System.Linq.Expressions.Expression.Constant(3),
            System.Linq.Expressions.Expression.Constant(2));

// Output the string representation of the Expression.
Console.WriteLine(newArrayExpression.ToString());

// This code produces the following output:
//
// new System.String[,](3, 2)
29.NewExpression

表示一个构造函数调用。
使用 New 工厂方法来创建 NewExpression 。对象的属性值 NodeType NewExpression 为 New 。

// Create a NewExpression that represents constructing
// a new instance of Dictionary<int, string>.
System.Linq.Expressions.NewExpression newDictionaryExpression =
    System.Linq.Expressions.Expression.New(typeof(Dictionary<int, string>));

Console.WriteLine(newDictionaryExpression.ToString());

// This code produces the following output:
//
// new Dictionary`2()
30.ParameterExpression

表示一个命名的参数表达式。
使用 Parameter 工厂方法来创建 ParameterExpression 。对象的属性值 NodeType ParameterExpression 为 Parameter 。

// Add the following directive to the file:
// using System.Linq.Expressions;

// Creating a parameter for the expression tree.
ParameterExpression param = Expression.Parameter(typeof(int));

// Creating an expression for the method call and specifying its parameter.
MethodCallExpression methodCall = Expression.Call(
    typeof(Console).GetMethod("WriteLine", new Type[] { typeof(int) }),
    param
);

// The following statement first creates an expression tree,
// then compiles it, and then runs it.
Expression.Lambda<Action<int>>(
    methodCall,
    new ParameterExpression[] { param }
).Compile()(10);

// This code example produces the following output:
//
// 10
31.RuntimeVariablesExpression

一个为变量提供运行时读/写权限的表达式。
此类型是在动态语言中实现 “eval” 所必需的。 它在运行时计算为的实例 IList 。

32.SwitchCase

表示 SwitchExpression 的一个事例。

// Add the following directive to the file:
// using System.Linq.Expressions;

// An expression that represents the switch value.
ConstantExpression switchValue = Expression.Constant(2);

// This expression represents a switch statement
// without a default case.
SwitchExpression switchExpr =
    Expression.Switch(
        switchValue,
        new SwitchCase[] {
            Expression.SwitchCase(
                Expression.Call(
                    null,
                    typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),
                    Expression.Constant("First")
                ),
                Expression.Constant(1)
            ),
            Expression.SwitchCase(
                Expression.Call(
                    null,
                    typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),
                    Expression.Constant("Second")
                ),
                Expression.Constant(2)
            )
        }
    );

// The following statement first creates an expression tree,
// then compiles it, and then runs it.
Expression.Lambda<Action>(switchExpr).Compile()();

// This code example produces the following output:
//
// Second
33.SwitchExpression

表示一个控制表达式,该表达式通过将控制传递到 SwitchCase 来处理多重选择。

// Add the following directive to the file:
// using System.Linq.Expressions;

// An expression that represents the switch value.
ConstantExpression switchValue = Expression.Constant(3);

// This expression represents a switch statement
// that has a default case.
SwitchExpression switchExpr =
    Expression.Switch(
        switchValue,
        Expression.Call(
                    null,
                    typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),
                    Expression.Constant("Default")
                ),
        new SwitchCase[] {
            Expression.SwitchCase(
                Expression.Call(
                    null,
                    typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),
                    Expression.Constant("First")
                ),
                Expression.Constant(1)
            ),
            Expression.SwitchCase(
                Expression.Call(
                    null,
                    typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),
                    Expression.Constant("Second")
                ),
                Expression.Constant(2)
            )
        }
    );

// The following statement first creates an expression tree,
// then compiles it, and then runs it.
Expression.Lambda<Action>(switchExpr).Compile()();

// This code example produces the following output:
//
// Default
34.SymbolDocumentInfo

存储用于发出源文件调试符号信息所必要的信息,尤其是文件名和唯一的语言标识符。详情地址

35.TryExpression

表示一个 try/catch/finally/fault 块。
注解:主体块受 try 块保护。处理程序包含一组 CatchBlock 表达式,这些表达式可以是 catch 语句或筛选器。如果引发了异常,则会运行错误块。不管控件如何退出正文,都将运行 finally 块。只能提供 fault 或 finally 块中的一个。Try 块的返回类型必须与任何关联 catch 语句的返回类型相匹配。

// Add the following directive to the file:
// using System.Linq.Expressions;

// A TryExpression object that has a Catch statement.
// The return types of the Try block and all Catch blocks must be the same.
TryExpression tryCatchExpr =
    Expression.TryCatch(
        Expression.Block(
            Expression.Throw(Expression.Constant(new DivideByZeroException())),
            Expression.Constant("Try block")
        ),
        Expression.Catch(
            typeof(DivideByZeroException),
            Expression.Constant("Catch block")
        )
    );

// The following statement first creates an expression tree,
// then compiles it, and then runs it.
// If the exception is caught,
// the result of the TryExpression is the last statement
// of the corresponding Catch statement.
Console.WriteLine(Expression.Lambda<Func<string>>(tryCatchExpr).Compile()());

// This code example produces the following output:
//
// Catch block
36.TypeBinaryExpression

表示表达式和类型之间的操作。
注解类型测试是表达式和类型之间的操作的示例。使用 TypeIs 工厂方法来创建TypeBinaryExpression。对象的属性值 NodeType TypeBinaryExpression 为 TypeIs 。

// Create a TypeBinaryExpression that represents a
// type test of the string "spruce" against the 'int' type.
System.Linq.Expressions.TypeBinaryExpression typeBinaryExpression =
    System.Linq.Expressions.Expression.TypeIs(
        System.Linq.Expressions.Expression.Constant("spruce"),
        typeof(int));

Console.WriteLine(typeBinaryExpression.ToString());

// This code produces the following output:
//
// ("spruce" Is Int32)
37.UnaryExpression

表示具有一元运算符的表达式。
注解
下表汇总了可用于创建 UnaryExpression 具有特定节点类型的的工厂方法。

NodeType工厂方法
ArrayLengthArrayLength
ConvertConvert
ConvertCheckedConvertChecked
NegateNegate
NegateCheckedNegateChecked
NotNot
QuoteQuote
TypeAsTypeAs
UnaryPlusUnaryPlus

此外, MakeUnary 还可以使用这些方法来创建 UnaryExpression 。 这些工厂方法可用于创建 UnaryExpression 表示一元运算的任何节点类型的。 类型为的这些方法的参数指定所 NodeType 需的节点类型。
示例
下面的示例创建一个 UnaryExpression 对象,该对象表示不可为 null 的整数表达式到可为 null 的整数类型的引用转换。

// Create a UnaryExpression that represents a
// conversion of an int to an int?.
System.Linq.Expressions.UnaryExpression typeAsExpression =
    System.Linq.Expressions.Expression.TypeAs(
        System.Linq.Expressions.Expression.Constant(34, typeof(int)),
        typeof(int?));

Console.WriteLine(typeAsExpression.ToString());

// This code produces the following output:
//
// (34 As Nullable`1)
38.MemberAssignment

表示对象的字段或属性的赋值操作。
使用 Bind 工厂方法来创建 MemberAssignment 。的 MemberAssignment BindingType 属性等于 Assignment 。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值