开发者

Checked type-cast in an Expression Tree?

开发者 https://www.devze.com 2023-03-15 09:41 出处:网络
I am usi开发者_StackOverflow社区ng 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

I am usi开发者_StackOverflow社区ng 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消