2011-07-19 65 views
2

代碼:爲什麼隱式轉換爲int轉換和截斷小數?

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; } 
} 

OUTPUT: int是:1個 小數是:2.5

註釋出:

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

OUTPUT: int是:1個 小數是:1

第二個版本運行時發生了什麼,兩種情況都輸出1?

回答

4

我的猜測是,編譯器看到,有一個隱式轉換從Bint,並從int隱式(內置)轉換爲decimal,使其既可以按順序使用。換句話說,電話變成D((decimal)(int)b)

請注意,沒有東西被截斷;相反,int正被提升爲decimal。如果您註釋掉int轉換,我預計I(b)將失敗,因爲即使存在從Bdecimal的隱式轉換,也不會從decimal轉換爲int

+0

我認爲你是對的 - 我認爲這不會編譯BEC。 D(2.5)沒有編譯,但我只是嘗試了D(2.5m),並且確定它已經工作了......謝謝! –

+0

@ Gabriel:可能是因爲'2.5'是一個'double',正如你明顯意識到的那樣:-) –

1
在您發表評論該行出它需要整型運算符,因爲有INT爲十進制的隱式轉換

...