[英]Runtime InvalidCastException with implicit cast operator
我有一个内部客户端使用VB.Net配置的C#库
他们的脚本抛出了InvalidCastException
,而这实际上是不应该的。
所以代码是这样的(大大简化):
//C#3
public class Foo {
public static implicit operator Foo ( Bar input )
{
return new Foo( input.Property1, input.Property2 );
}
}
然后在他们的VB.Net中(再次大大简化):
Dim fc = New FooCollection()
Dim b as Bar = GetBar()
fc(fooIndex) = b 'throws InvalidCastException at runtime!
如果我在隐式/加宽运算符内添加断点,它将永远无法到达。
如果删除隐式运算符,它将无法编译。
如果我在C#中执行等效语句:
var fc = new FooCollection();
Bar b = GetBar();
fc[fooIndex] = b //it works!
奇怪-看起来VB.net编译器可以找到强制转换运算符,但它在运行时丢失。 当然,VB和C#IL在这里会非常相似吗?
VB.net代码是动态编译的-编译发生在用户首次登录应用程序时。 它针对.Net 3.5被编译为VB.Net,并且我没有使用任何COM互操作。
有任何想法吗?
首先,我尝试将C#程序集标记为CLSCompliant(true)
以查看这是否对implicit operator Foo
生成任何警告。
啊哈, 这里是:
问题在于VB.NET根本不调用C#代码公开的
op_Implicit
/op_Explicit
函数。 深入研究Visual Basic引擎,您可以发现它在ICovertible
使用ICovertible
进行了所有转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.