【发布时间】:2018-05-08 19:14:20
【问题描述】:
这是从MSDN复制的示例。
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()();
//Default
它工作正常,将“默认”打印到控制台。
我的问题是如何使表达式符合下一种情况(“第一”)。这是我尝试过的:
ParameterExpression pe = Expression.Parameter(typeof(int));
Expression.Lambda<Action<int>>(switchExpr,pe).Compile()(1);
//
ParameterExpression peo = Expression.Parameter(typeof(object));
object o = 1;
Expression.Lambda<Action<object>>(switchExpr, peo).Compile()(o);
他们都没有将“First”打印到控制台。怎么了?谢谢。
更新:
我认为MSDN的代码不是一个完美的例子,为什么要打开一个常量?
【问题讨论】:
标签: c# lambda expression