我有这样的结构,显式转换为float:
struct TwFix32
{
public static explicit operator float(TwFix32 x) { ... }
}
Run Code Online (Sandbox Code Playgroud)
我可以使用一个显式转换将TwFix32转换为int: (int)fix32
但要将其转换为十进制,我必须使用两个强制转换: (decimal)(float)fix32
没有从float到int或decimal的隐式转换.为什么编译器让我在进入int时省略了浮动的中间转换,但是当我要去小数时呢?
考虑以下代码:
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!
}
Run Code Online (Sandbox Code Playgroud)
我根本不希望它编译,因为没有从十进制隐式转换?到十进制。
我认为这是一个错误还是我做错了什么?
我已经看到了这一点: 从 int 提升/可空转换的严重错误,允许从十进制转换
但这看起来不一样,而且已经过时了(7 年以上),所以现在应该修复错误,但无法确定,因为所有指向错误报告的链接都消失了)... :(
我真的很想在真正的解决方案中使用这样的代码(跟踪计算),但这阻止了我。
PS:我在 Windows 上编译。