使用布尔值扩展运算符
我正在尝试将布尔值装箱以在我的代码中共享它。我在使用加宽运算符(C# 中的隐式运算符)来简化事物时遇到问题。
Public Class CancellationToken
Public Property IsCancelled As Boolean
Public Shared Widening Operator CType(a As CancellationToken) As Boolean
Return a.IsCancelled
End Operator
End Class
以下代码工作正常:
Sub DoIt(IsCancelled As CancellationToken)
Do Until IsCancelled
...
Loop
End Sub
但此块报告编译时错误:未为类型“CancellationToken”和“Boolean”定义运算符“Or”。
Sub DoIt(IsCancelled As CancellationToken)
Dim ContentLength As Long = ...
Do Until IsCancelled OrElse ContentLength = 0
...
Loop
End Sub
显然,ContentLength = 0
被评估为布尔值。鉴于 OrElse
期望每一侧都有一个布尔值,为什么 IsCancelled
不隐式转换为布尔值?
创建 IsTrue
、IsFalse
、Or
和 And
运算符也无法解决问题。我启用了 Option Explicit 和 Option Strict。
I'm trying to box a Boolean value to share it around my code. I'm having trouble using a Widening Operator (implicit operator in C#) to simply things.
Public Class CancellationToken
Public Property IsCancelled As Boolean
Public Shared Widening Operator CType(a As CancellationToken) As Boolean
Return a.IsCancelled
End Operator
End Class
The following code works fine:
Sub DoIt(IsCancelled As CancellationToken)
Do Until IsCancelled
...
Loop
End Sub
But this block reports a compile time error: Operator 'Or' is not defined for types 'CancellationToken' and 'Boolean'.
Sub DoIt(IsCancelled As CancellationToken)
Dim ContentLength As Long = ...
Do Until IsCancelled OrElse ContentLength = 0
...
Loop
End Sub
Clearly it's evaluated ContentLength = 0
to a boolean. Given OrElse
expects a Boolean on each side, why isn't IsCancelled
implicitly converted to a Boolean?
Creating IsTrue
, IsFalse
, Or
, and And
operators don't rectify the problem either. I have Option Explicit and Option Strict enabled.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,请注意它仅适用于 C#。但是,在这种情况下 VB 编译器可能想要使用
IsTrue
/IsFalse
运算符:(源)
因此:添加一个
IsTrue()
和IsFalse()
,也许除了一个Or()
(尽管我会先尝试不使用Or()
)。Firstly, note that it just works in C#. However, it is possible that in this case the VB compiler wants to use the
IsTrue
/IsFalse
operators:(source)
So: add an
IsTrue()
andIsFalse()
, perhaps in addition to anOr()
(although I'd try without theOr()
first).