考虑以下代码:
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 fromstruct S
tostring
, then a "lifted" conversion fromS?
tostring
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/