gpt4 book ai didi

c# - Expression.Convert 不会为不变值类型参数抛出 InvalidOperationException?

转载 作者:太空狗 更新时间:2023-10-29 22:54:07 25 4
gpt4 key购买 nike

Expression.Convert 一般投入 InvalidOperationException“表达式.Type 和类型之间没有定义转换运算符。”

Func<>的返回类型参数对于引用类型是协变的。

// This works.
Func<SomeType> a = () => new SomeType();
Func<object> b = a;

isn't covariant for value types .

Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type.

// This doesn't work!
Func<int> five = () => 5;
Func<object> fiveCovariant = five;

然而,Expression.Convert相信这是可能的。

Func<int> answer = () => 42;
Expression answerExpression = Expression.Constant( answer );
// No InvalidOperationException is thrown at this line.
Expression converted
= Expression.Convert( answerExpression, typeof( Func<object> ) );

没有InvalidOperationException调用 Expression.Convert 时抛出.表达式树编译正确,但是当我调用创建的委托(delegate)时,我得到了预期的 InvalidCastException .

  1. 这是一个错误吗? ( I reported it as a bug on Microsoft Connect .)
  2. 如何正确检查一种类型是否可以转换为另一种类型? Some answers似乎是指使用 Convert .我非常喜欢一种不必使用异常处理作为逻辑的方法。

似乎没有正确支持整个方差逻辑。它正确地提示无法从 Func<SomeType> 转换至 Func<SomeOtherType> ,但它不会提示从 Func<object> 转换至 Func<string> .

有趣的是,一次SomeTypeSomeOtherType位于同一类层次结构中( SomeOtherTypeSomeType 扩展),它从不抛出异常。如果不是,那就是。

最佳答案

Is this a bug?

是的。当我们添加协变和逆变时,表达式树库可能没有始终如一地更新。对此感到抱歉。

I reported it as a bug on Microsoft Connect.

谢谢!到时候会有人看。

How to properly check whether a type can be converted to another type?

这个问题含糊不清。给定两个类型对象,你想知道:

  • .NET 运行时是否认为类型与赋值兼容?
  • C# 编译器是否认为类型之间存在隐式转换?
  • C# 编译器是否认为类型之间存在显式转换?

例如,“int”和“short”不符合 .NET 规则的赋值。根据 C# 规则,Int 可以显式转换但不能隐式转换为 short,而 short 可以隐式和显式转换为 int。

关于c# - Expression.Convert 不会为不变值类型参数抛出 InvalidOperationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7960018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com