小编Car*_*fex的帖子

使用非常量表达式切换语句 - 扩展C#/ IDE能力

在你开始批评并指出我的C#规范的 §8.7.2之前,请仔细阅读:)

我们都知道C#中的switch是怎样的.好的,请考虑MainWindow使用"讨厌的" Bar方法

static int barCounter = 0;
public static int Bar()
{
    return ++barCounter;
}
Run Code Online (Sandbox Code Playgroud)

在这个类的某个地方,我们有这样的代码

Action switchCode = () =>
{
    switch (Bar())
    {
        case 1:
            Console.WriteLine("First");
            break;
        case 2:
            Console.WriteLine("Second");
            break;
    }
};

switchCode();

switchCode();
Run Code Online (Sandbox Code Playgroud)

在控制台窗口中,我们将看到

First
Second
Run Code Online (Sandbox Code Playgroud)

在C#中使用表达式我们也可以这样做 - 编写相同的代码

var switchValue = Expression.Call(typeof(MainWindow).GetMethod("Bar"));

var WriteLine = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) });

var @switch = Expression.Switch(switchValue,
    Expression.SwitchCase(
        Expression.Call(WriteLine, Expression.Constant("First")),
        Expression.Constant(1)
        ),
    Expression.SwitchCase(
        Expression.Call(WriteLine, Expression.Constant("Second")),
        Expression.Constant(2)
        )
    );

Action switchCode = …
Run Code Online (Sandbox Code Playgroud)

.net c# compiler-construction expression switch-statement

5
推荐指数
1
解决办法
4131
查看次数