什么是起重操作员?
我正在查看这篇文章努力遵循解释提升运算符的 VB.NET 示例。似乎没有等效的 C# 示例或教程。一般来说,我在运算符重载方面没有太多经验,因此在阅读可空类型的同时尝试接受 VB.NET 等效项可能不是最好的起点...
是否有人能够提供一个提升运算符的解释以及可空类型如何使用它们?这是否仅仅意味着可空类型本身不会重载运算符,并且将使用它所代表的基础类型中的运算符?
似乎没有太多关于提升操作员的信息,所以希望这也能帮助其他人。
I was looking at this article and am struggling to follow the VB.NET example that explains lifted operators. There doesn't seem to be an equivalent C# example or tutorial. I don't have much experience with operator overloading in general, so trying to come to terms with the VB.NET equivalent whilst reading up on nullable types probably isn't the best place to start...
Would anyone be able to provide an explanation of lifted operators and how they are used by nullable types? Does it just mean that the nullable type does not itself overload operators and will use the operators from the underlying type that it represents?
There doesn't seem to be much information on SO about lifted operators, so hopefully this can help some others out too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
提升运算符允许将适用于不可空类型的预定义和用户定义运算符也用于其可空形式。
Lifted operators allow predefined and user-defined operators that work for non-nullable types to be used for their nullable forms as well.
提升运算符是通过“提升”非可为空形式上已存在的运算符来处理可为空类型的运算符。例如,如果您这样做:
则“+”运算符将被解除。它实际上并不存在于
Nullable
上,但 C# 编译器的行为就像它存在一样,生成代码来执行正确的操作。 (在大多数情况下,需要检查任一操作数是否为 null;如果是,则结果为 null。否则,将两个操作数解包为其不可为 null 的值,使用普通运算符,然后将结果包装回可为 null 的值。不过,比较有一些特殊情况。)请参阅 C# 规范 了解更多信息。
Lifted operators are operators which work over nullable types by "lifting" the operators which already exist on the non-nullable form. So for example, if you do:
That "+" operator is lifted. It doesn't actually exist on
Nullable<int>
but the C# compiler acts as if it does, generating code to do the right thing. (For the most case, that's a matter of checking whether either operand is null; if so, the result is null. Otherwise, unwrap both operands to their non-nullable values, use the normal operator, and then wrap the result back into a nullable value. There are a few special cases around comparisons though.)See section 6.4.2 (lifted conversion operators) and 7.3.7 (lifted operators) of the C# spec for more information.