C# 编译器错误 : allows for conversion from Nullable<decimal> to decimal

标签 c# type-conversion operator-overloading compiler-bug

考虑以下代码:

    public class DecimalWrapper
    {
        public static implicit operator DecimalWrapper(decimal x) => new();
    }

    [Fact]
    public void Test()
    {
        // Why this even compiles? Since there is no implicit conversion from decimal? -> decimal
        DecimalWrapper c = (decimal?)null; // variable 'c' is null!
    }

我根本不希望它能够编译,因为没有从十进制进行隐式转换?到十进制。

我认为这是一个错误还是我弄错了什么?

我看过这个: Serious bugs with lifted/nullable conversions from int, allowing conversion from decimal

但这看起来不同,而且已经很旧了(7年多了),所以现在应该修复错误,但不能确定,因为所有错误报告的链接都消失了)...:(

我真的很想在实际解决方案中使用这样的代码(跟踪计算),但这阻止了我。

PS:我在 Windows 上编译。

最佳答案

根据specification提升转换运算符仅适用于值类型到值类型的转换(及其可为 null 的对应项),但在 Roslyn 编译器中 source code您可以找到下一条评论:

DELIBERATE SPEC VIOLATION:
The native compiler allows for a "lifted" conversion even when the return type of the conversion not a non-nullable value type. For example, if we have a conversion from struct S to string, then a "lifted" conversion from S? to string is considered by the native compiler to exist, with the semantics of "s.HasValue ? (string)s.Value : (string)null". The Roslyn compiler perpetuates this error for the sake of backwards compatibility.

所以这似乎是一个实际的错误,是为了向后兼容而引入的。还有decompilation准确地显示了这种行为。

关于C# 编译器错误 : allows for conversion from Nullable<decimal> to decimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68922785/

相关文章:

c# - 传入字典的模型项在 ASP.net MVC 中属于“System.Collections.Generic.List...”类型

c# - 单元测试时无法读取应用程序设置

Java:是否可以将一个参数化类型用于另一个参数化类型?

java - 如何将 double 转换为对象?

c++ - 使用什么代码更好地进行运算符重载

objective-c - 我可以在 Objective-C 中重载运算符吗?

C# TreeView.EnsureVisible() - 我还能如何滚动?

c# - 可以运行 2 个后台任务 - Windows Phone 8.1 通用应用程序?

type-conversion - 当 std_logic_vector 的大小可参数化时,如何计算其所需的位数?

c++ - 有没有办法覆盖括号的默认行为?