Это пример, скопированный с 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
Работает нормально, выводит «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" на консоль. в чем дело? ТНХ.
UPDATE:
Я думаю, что код MSDN не идеальный пример, зачем включать константу?