使用布尔值扩展运算符

发布于 2024-12-12 08:27:28 字数 946 浏览 0 评论 0原文

我正在尝试将布尔值装箱以在我的代码中共享它。我在使用加宽运算符(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 不隐式转换为布尔值?

创建 IsTrueIsFalseOrAnd 运算符也无法解决问题。我启用了 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

计㈡愣 2024-12-19 08:27:28

首先,请注意它仅适用于 C#。但是,在这种情况下 VB 编译器可能想要使用 IsTrue/IsFalse 运算符:

重载 Or 和 IsTrue 运算符会影响 OrElse 运算符的行为。

因此:添加一个 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:

Overloading the Or and IsTrue operators affects the behavior of the OrElse operator.

(source)

So: add an IsTrue() and IsFalse(), perhaps in addition to an Or() (although I'd try without the Or() first).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文