问题描述
我使用表达式来创建动态生成的代码一点点。我的解决方案的工作原理,但有一个特点:我想要做一个检查类型转换,其中,如果转换失败TypeCastException被抛出
我发现Expression.TypeAs( ),该函数执行类型转换,但它返回null,而不是抛出,当转换失败。
有一个简单的方法做一个检查类型转换中表达? ?还是我检查null,并抛出该异常自己
下面是我有: -
ParameterExpression typedAttribute = Expression.Variable(属性,typedAttribute);
ParameterExpression的TypedValue = Expression.Variable(VALUETYPE的TypedValue);
BlockExpression methodBlock = Expression.Block(新[] {typedAttribute,的TypedValue},新的Expression []
{
Expression.Assign(typedAttribute,Expression.TypeAs(属性,属性类型)),
Expression.Assign(的TypedValue,Expression.TypeAs(值,值类型)),
Expression.Call(游客,MethodInfo的,typedAttribute,的TypedValue),
Expression.Assign(参观, Expression.Constant(真)),
});
Expression.Convert
应作为这里铸造。
I am using Expression to create a little bit of dynamically-generated code. My solution works, except for one feature: I want to do a checked type-cast, where TypeCastException is thrown if the cast fails.
I have found Expression.TypeAs(), which does the type conversion, but it returns null, rather than throwing, when the cast fails.
Is there a simple way to do a checked type-cast in Expression? Or do I have to check for null and throw the exception myself?
Here's what I have: -
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
should act as a cast here.
这篇关于经过类型转换在一个表达式树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!