Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在运行时构建范围开关大小写表达式?_C#_Switch Statement_Expression_Expression Trees - Fatal编程技术网

C# 如何在运行时构建范围开关大小写表达式?

C# 如何在运行时构建范围开关大小写表达式?,c#,switch-statement,expression,expression-trees,C#,Switch Statement,Expression,Expression Trees,我正在构建一个开关表达式,以便在运行时匹配整数的范围。 目前,我能够使用Expression.SwitchCase编译并运行以下等效程序: switch(value) { case 1: case 2: Console.WriteLine("1 or 2"); break; case 3: case 4: case 5: Console.WriteLine("3, 4 or 5"); brea

我正在构建一个开关表达式,以便在运行时匹配整数的范围。 目前,我能够使用
Expression.SwitchCase
编译并运行以下等效程序:

switch(value)
{
    case 1:
    case 2:
        Console.WriteLine("1 or 2");
        break;
    case 3:
    case 4:
    case 5:
        Console.WriteLine("3, 4 or 5");
        break;
}
我的问题是-我必须为我希望匹配的范围内的每个常数创建一个SwitchCase:

Expression.SwitchCase(body,Expression.Constant(1))

Expression.SwitchCase(body,Expression.Constant(2))


有没有更简洁的方法来实现这一点?是否有一种方法可以将该常量表达式替换为根据范围计算切换值的表达式?。性能也很重要,特别是在范围较大的情况下。

您可以使用其他超负荷的

只需创建一个带有测试值的数组,并将其转换为
ConstantExpression
。试试这个例子:

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

// body of first block
var action1 = Expression.Call(writeLine, Expression.Constant("1 or 2"));
// body of second block
var action2 = Expression.Call(writeLine, Expression.Constant("3, 4 or 5"));

var value = Expression.Parameter(typeof(int), "value");
var body = Expression.Switch(value,
    Expression.SwitchCase(
      action1,
      new[] {1, 2}.Select(i => Expression.Constant(i))),
    Expression.SwitchCase(
      action2, 
      new[] {3, 4, 5}.Select(i => Expression.Constant(i)))
);

var lambda = Expression.Lambda<Action<int>>(body, value);
var method = lambda.Compile();

method(1); // print "1 or 2"
method(4); // print "3, 4 or 5"
var writeLine=typeof(Console).GetMethod(“writeLine”,新[]{typeof(string)});
//第一区块主体
var action1=Expression.Call(writeLine,Expression.Constant(“1或2”));
//第二块体
var action2=Expression.Call(writeLine、Expression.Constant(“3、4或5”);
var值=表达式参数(typeof(int),“value”);
变量体=表达式.Switch(值,
开关盒(
行动1,
new[]{1,2}.Select(i=>Expression.Constant(i)),
开关盒(
行动2,
new[]{3,4,5}.Select(i=>Expression.Constant(i)))
);
var lambda=表达式.lambda(主体,值);
var method=lambda.Compile();
方法(1);//打印“1或2”
方法(4);//打印“3、4或5”

您看过这个问题了吗?是的,这正是我想要实现的结果,但我想知道是否可以在运行时使用表达式进行构建。