2012-09-06 120 views
3

我有下面的代碼控制檯應用程序:int字段的默認值爲0嗎?

using System; 

    namespace HeadfirstPage210bill 
    { 
     class Program 
     { 
      static void Main(string[] args) 
      { 
       CableBill myBill = new CableBill(4); 
       Console.WriteLine(myBill.iGotChanged); 
       Console.WriteLine(myBill.CalculateAmount(7).ToString("£##,#0.00")); 
       Console.WriteLine("Press enter to exit"); 
       Console.WriteLine(myBill.iGotChanged); 
       Console.Read(); 
      } 
     } 
    } 

類CableBill.cs如下:

using System; 

    namespace HeadfirstPage210bill 
    { 
     class CableBill 
     { 
      private int rentalFee; 
      public CableBill(int rentalFee) { 
       iGotChanged = 0; 
       this.rentalFee = rentalFee; 
       discount = false; 
      } 

      public int iGotChanged = 0; 


      private int payPerViewDiscount; 
      private bool discount; 
      public bool Discount { 
       set { 
        discount = value; 
        if (discount) { 
         payPerViewDiscount = 2; 
         iGotChanged = 1; 
        } else { 
         payPerViewDiscount = 0; 
         iGotChanged = 2; 
        } 
       } 
      } 

      public int CalculateAmount(int payPerViewMoviesOrdered) { 
       return (rentalFee - payPerViewDiscount) * payPerViewMoviesOrdered; 
      } 

     } 
    } 

該控制檯返回以下:

enter image description here

我看不到的是當payPerViewDiscount設置爲0.當然,這隻有在Discou nt屬性已設置,但如果調用屬性Discount,則變量iGotChanged應該返回1或2,但它似乎保持爲0.因爲它是int類型,因此payPerViewDiscount的默認值爲0?

回答

9

是INT的默認值是0您可以檢查使用default關鍵字

int t = default(int); 

t將舉行0

+0

+1謝謝 - 我認爲這可能是這種情況,但它似乎有點違背語言的強類型安全基礎 – whytheq

+0

類型安全的嚴格性?怎麼來的 ? – Habib

+0

我真的沒有正確表達它的意思......它看起來像一個非常嚴格的語言,但這種默認似乎違反嚴格? ...我有什麼意義 – whytheq

1

是的,zero是int的默認值。

3

在構造函數運行之前,類中的字段被初始化爲默認值。 int的默認值爲0.

請注意,這是而不是適用於局部變量,例如,在方法中。他們不會自動初始化。

public class X 
{ 
    private int _field; 

    public void PrintField() 
    { 
     Console.WriteLine(_field); // prints 0 
    } 

    public void PrintLocal() 
    { 
     int local; 
     Console.WriteLine(local); 
     // yields compiler error "Use of unassigned local variable 'local'" 
    } 
} 
+0

感謝額外的筆記本地變量 - 懷疑我可能已經結束了我的腦袋在未來 – whytheq