代码:
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 时,发生了什么?
最佳答案
我的猜测是编译器发现存在从 B
到 int
的隐式转换,以及从 int< 的隐式(内置)转换
转换为十进制
,以便可以按顺序使用两者。换句话说,调用变为D((decimal)(int)b)
。
请注意,没有任何内容被截断;相反,int
被提升为decimal
。相反,如果您注释掉 int
转换,我预计 I(b)
将会失败,因为即使存在来自 B
的隐式转换到 decimal
,没有从 decimal
到 int
的隐式转换。
关于c# - 为什么隐式转换为 int 会转换并截断小数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6755178/