Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.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#_Expression Trees - Fatal编程技术网

C# 选中表达式树中的类型强制转换?

C# 选中表达式树中的类型强制转换?,c#,expression-trees,C#,Expression Trees,我使用Expression创建了一点动态生成的代码。我的解决方案是有效的,除了一个特性:我想做一个选中类型转换,如果转换失败,就会抛出TypeCastException 我找到了Expression.TypeAs(),它进行类型转换,但当强制转换失败时,它返回null而不是抛出 有没有一种简单的方法可以在表达式中执行选中类型强制转换?还是我必须检查null并自己抛出异常 以下是我所拥有的:- ParameterExpression typedAttribute = Expression.Vari

我使用Expression创建了一点动态生成的代码。我的解决方案是有效的,除了一个特性:我想做一个选中类型转换,如果转换失败,就会抛出TypeCastException

我找到了Expression.TypeAs(),它进行类型转换,但当强制转换失败时,它返回null而不是抛出

有没有一种简单的方法可以在表达式中执行选中类型强制转换?还是我必须检查null并自己抛出异常

以下是我所拥有的:-

ParameterExpression typedAttribute = Expression.Variable(attributeType, "typedAttribute");
ParameterExpression typedValue = Expression.Variable(valueType, "typedValue");

BlockExpression methodBlock = Expression.Block(new[] { typedAttribute, typedValue }, new Expression[]
   {
       Expression.Assign(typedAttribute, Expression.TypeAs(attribute, attributeType)),
       Expression.Assign(typedValue, Expression.TypeAs(value, valueType)),
       Expression.Call(visitor, methodInfo, typedAttribute, typedValue),
       Expression.Assign(visited, Expression.Constant(true)),
   });

Expression.Convert
应该在这里扮演演员角色。

谢谢,这很有效。事实上,我记得我之前尝试过Expression.Convert(),但我想当时我的代码中有另一个错误,这使我无法看到它是正确的解决方案。无论如何,很高兴这么快就有了一个明确的答案!有更快的演员阵容吗?我正在创建已编译的setter/getter,但是对对象的装箱取消装箱会减慢速度。@Demetris then:不要使用装箱数据。。。如果没有,很难说得更多context@MarcGravell首先,感谢您的投入。所以你是说避免valuetype到object,或者一般来说避免任何类型到object?我需要Func和Action的通用“接口”——特别是级联“elvis”类调用。@Demetris具有Func对象或类似对象,并使用值类型,避免装箱以获得最佳性能。。。你不可能三个都有。