有没有办法在 VB.NET 中定义隐式转换运算符? [英] Is there a way to define an implicit conversion operator in VB.NET?
问题描述
在 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....
我在 加宽
运算符.显然,CType Widening
运算符是调用"的.对于隐式转换,而 CType Narrowing
运算符用于显式转换.
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.
例如,以下内容会将 Something
类型隐式转换为 MyClass
.它正确调用了我的 Widening
转换实现,并且一切正常:
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.
例如,以下代码将在 Something
在 For Each
循环中,类型被隐式转换为 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
非常感谢您对此的任何见解.
Any insight on this is greatly appreciated.
推荐答案
在 VB.NET 中,使用 Widening 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
相反,显式转换,可以通过将上述定义中的 Narrowing
替换为 Widening
来完成.
The opposite, an explicit conversion, can be done by swapping Narrowing
for Widening
in the above definition.
这篇关于有没有办法在 VB.NET 中定义隐式转换运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!