Проблема соответствия Expression.SwitchCase - PullRequest
0 голосов
/ 08 мая 2018

Это пример, скопированный с 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 не идеальный пример, зачем включать константу?

Ответы [ 2 ]

0 голосов
/ 08 мая 2018

Спасибо @Ignacio за выяснение проблемы.

Вот код, который я придумал. enter image description here

полный код

ParameterExpression pe = Expression.Parameter(typeof(int));

SwitchExpression switchExpr =
    Expression.Switch(
        pe,
        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)
            )
        }
    );

var action = Expression.Lambda<Action<int>>(switchExpr,pe).Compile();
action(1);
action(2);
action(3);
0 голосов
/ 08 мая 2018

В примере, представленном на этой странице, вы можете увидеть, как вывести «Второе» значение:

https://msdn.microsoft.com/en-us/library/system.linq.expressions.switchcase(v=vs.110).aspx

Ваш пример вообще не использует значение, а использует фиксированные 3 в начале примера:

ConstantExpression switchValue = Expression.Constant(3);

Надеюсь, это поможет.

...