有没有一种方法来定义在VB.NET中的隐式转换操作符?方法来、定义、操作、隐式

2023-09-02 02:01:29 作者:再逼我就用豆腐撞墙

在C#中,您可以使用隐含关键字来定义隐式的用户定义类型转换操作符。

In C#, you can use the implicit keyword to define an implicit user-defined type conversion operator.

在VB.NET,你可以定义一个 CTYPE 转换运算符将明确转换一个用户定义类型到另一种类型。

In VB.NET, you can define a CType conversion operator that will explicitly convert a user-defined type into another type.

有没有一种方法来声明在VB.NET中的隐式转换操作符?

Is there a way to declare an implicit conversion operator in VB.NET?

我似乎无法找到这方面的消息......

I can't seem to find any information on this....

我发现我的答案MSDN文档的Widening运营商。显然,CTYPE 拓宽运算符称为隐式转换而CTYPE的 缩小 运营商的要求显式转换。

I found my answer in the MSDN documentation for the Widening operator. Apparently the CType Widening operator is "called" for implicit conversions whereas the CType Narrowing operator is called for explicit conversions.

起初,我以为本文档是不正确的,因为我遇到了在测试过程中的异常。我再次测试,发现了一些很奇怪的。我实现了扩大转换操作符的功能正常工作时使用=运营商做隐式转换的。

At first, I thought this documentation was incorrect, because I was experiencing an exception during testing. I re-tested and found something very strange. The function I implemented as the widening conversion operator works fine when an implicit cast is done using the "=" operator.

例如,下面将隐式转换的的东西键入 MyClass的。它正确地叫我拓宽转换执行和一切正常,没有错误:

For example, the following will implicitly cast the Something type into MyClass. It calls my Widening conversion implementation correctly and everything works without error:

Dim y As Something
Dim x As MyClass = y

但是,如果隐式转换是在一个的foreach 循环完成的,这是行不通的。

However, if the implicit cast is done in a foreach loop, it does not work.

例如,下面的code将抛出一个异常(无法转换类型'东西'输入的对象MyClass的的)时,的东西类型隐式强制转换为 MyClass的对于每个循环:

For example, the following code will throw an exception ("Unable to cast object of type 'Something' to type 'MyClass'") when the Something type is implicitly casted to MyClass in the For Each loop:

 Dim anArrayOfSomethingTypes() As Something  = getArrayOfSomethings()
 For Each x As MyType In anArrayOfSomethingTypes 
  ....
 Next

对此有何见解大大AP preciated。

Any insight on this is greatly appreciated.

推荐答案

在VB.NET中,使用加宽CTYPE运营商创建的隐式转换:

In VB.NET, use the Widening CType operator to create an implicit conversion:

Class C1
    Public Shared Widening Operator CType(ByVal p1 As C1) As C2

    End Operator
End Class

相反,显式转换,可以通过交换来完成缩小拓宽在上面的定义。