相关疑难解决方法(0)

在表达式树中检查了类型转换?

我正在使用Expression创建一些动态生成的代码.我的解决方案有效,除了一个功能:我想做一个检查类型转换,如果转换失败,则抛出TypeCastException.

我找到了Expression.TypeAs(),它执行类型转换,但是当转换失败时它返回null而不是throw.

有一种简单的方法可以在Expression中进行检查类型转换吗?或者我是否必须检查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)),
   });
Run Code Online (Sandbox Code Playgroud)

c# expression-trees

11
推荐指数
1
解决办法
2665
查看次数

typeof为未构造的嵌套泛型类型提供异常'Type expected`

通常使用typeof获取未构造的泛型类型非常简单:

Type genericType = typeof( Func<> );
Run Code Online (Sandbox Code Playgroud)

我希望以下内容也能正常工作,但它会产生编译错误Type expected.

Type genericNestedType = typeof( Func<Func<>> );
Run Code Online (Sandbox Code Playgroud)

通过Func<Func<object>>改为使用它来解决这个问题相对容易.但是,在你"消费"这种类型的地方,你必须记住打电话GetGenericTypeDefinition().

您可能希望"填满"所有未分配的泛型类型参数的方案是不可能的.同样,创建一个虚拟类型代替表示这些参数会相对容易.(例如Func<Func<ToReplace, object, int>>)

是否有任何理由typeof不适用于嵌套的通用未构造类型?

c# generics reflection typeof

6
推荐指数
1
解决办法
3608
查看次数

标签 统计

c# ×2

expression-trees ×1

generics ×1

reflection ×1

typeof ×1