【发布时间】:2015-11-20 11:06:57
【问题描述】:
我正在尝试实现 Expression.Switch() 以在我的表达式中创建一个 switch 语句。我正在努力解决一些问题。
我创建了一个引发异常的小示例。 switch 使用字符串来切换 case 并在 case 中分配一个变量。
下面是一些会引发异常的代码:
// an int variable
var var1 = Expression.Parameter(typeof(int));
// a string variable
var var2 = Expression.Parameter(typeof(string));
var cases = new[]
{
// the first case 'SwitchCaseValue1' should write the int value 1 into variable var1
Expression.SwitchCase(Expression.Assign(var1, Expression.Constant(1)), Expression.Constant("SwitchCaseValue1")),
// the second case 'SwitchCaseValue2' should write the string value 'Example' into variable var2
Expression.SwitchCase(Expression.Assign(var2, Expression.Constant("Example")), Expression.Constant("SwitchCaseValue2"))
};
Expression.Switch(Expression.Constant("SwitchValue"), cases);
这将引发此异常:All case bodies and the default body must have the same type.
我认为这是指 Assign 为案例 1 返回一个 int 和为案例 2 返回一个字符串。 我怎样才能不返回任何东西?
如果我将 var2 更改为 int:
// an int variable
var var1 = Expression.Parameter(typeof(int));
// a string variable
var var2 = Expression.Parameter(typeof(int));
var cases = new[]
{
// the first case 'SwitchCaseValue1' should write the int value 1 into variable var1
Expression.SwitchCase(Expression.Assign(var1, Expression.Constant(1)), Expression.Constant("SwitchCaseValue1")),
// the second case 'SwitchCaseValue2' should write the string value 'Example' into variable var2
Expression.SwitchCase(Expression.Assign(var2, Expression.Constant(2)), Expression.Constant("SwitchCaseValue2"))
};
Expression.Switch(Expression.Constant("SwitchValue"), cases);
引发异常:Default body must be supplied if case bodies are not System.Void.
所以我改变了:最后一行
Expression.Switch(Expression.Constant("SwitchValue"), Expression.Constant(0), cases);
这将编译。但不是我要找的...
是否有另一种方法来修复第一个解决方案,而无需实现额外的代码来返回相同的类型?
我不喜欢选择无意义的返回值之类的解决方案,例如:
// an int variable
var var1 = Expression.Parameter(typeof(int));
// a string variable
var var2 = Expression.Parameter(typeof(string));
var cases = new[]
{
// the first case 'SwitchCaseValue1' should write the int value 1 into variable var1
Expression.SwitchCase(
Expression.Block(
Expression.Assign(var1, Expression.Constant(1)),
// return a boolean
Expression.Constant(true)),
Expression.Constant("SwitchCaseValue1")),
// the second case 'SwitchCaseValue2' should write the string value 'Example' into variable var2
Expression.SwitchCase(
Expression.Block(
Expression.Assign(var2, Expression.Constant("Example")),
// return a boolean
Expression.Constant(true)),
Expression.Constant("SwitchCaseValue2"))
};
Expression.Switch(Expression.Constant("SwitchValue"), Expression.Constant(false), cases);
我了解表达式和返回值的逻辑。但是有没有办法避免实现无意义的代码?
【问题讨论】:
标签: c# expression