c# - 为什么隐式转换为 int 会转换并截断小数?

标签 c# implicit-conversion

代码:

void Main()
{
    C.F();
}
public class C
{
    public static void F()
    {
        var a = new A { i = 1, d = 2.5m };
        var b = new B(a);
        I(b);
        D(b);
    }
    static void I(int i) { Console.WriteLine("int is: " + i); }  
    static void D(decimal d) { Console.WriteLine("decimal is: " + d); }
}
public class A
{
    public int i;
    public decimal d;
}
public class B
{
    A _a;
    public B(A a) { _a = a; }
    public static implicit operator int(B b) { return b._a.i; }
    public static implicit operator decimal(B b) { return b._a.d; }
}

输出: 整数是:1 小数为:2.5

注释掉:

//public static implicit operator decimal(B b) { return b._a.d; }

输出: 整数是:1 小数为:1

当第二个版本运行并在两种情况下都输出 1 时,发生了什么?

最佳答案

我的猜测是编译器发现存在从 Bint 的隐式转换,以及从 int< 的隐式(内置)转换 转换为十进制,以便可以按顺序使用两者。换句话说,调用变为D((decimal)(int)b)

请注意,没有任何内容被截断;相反,int 被提升为decimal。相反,如果您注释掉 int 转换,我预计 I(b) 将会失败,因为即使存在来自 B 的隐式转换到 decimal,没有从 decimalint 的隐式转换。

关于c# - 为什么隐式转换为 int 会转换并截断小数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6755178/

相关文章:

c - 当 -1L、1U 和 -1UL 是符号常量时,-1L < 1U 和 -1L > UL 的输出与声明为枚举常量时不同

c - 有什么方法可以让 gcc 发出警告,以便在 C 中将隐式枚举转换为 int?

c++ - `is_base_of` 是如何工作的?

c# - 在 Code First Entity Framework Fluent API 中的模型生成期间设置默认日期值

c# - 针对每个 Web 请求和生命周期范围的 SimpleInjector 混合生活方式

c# - 当我尝试将属性路由与 Web API 2 结合使用时,为什么会出现 InvalidOperationException?

c# - 正则表达式 C# IsMatch()

string - 专用 Scala 字符串插值

Java:隐式类型转换,或隐式 toString() 调用

c# - Developer 和 MSbuild 命令提示符之间有什么区别