int字段的默认值为0吗?

问题描述:

我有下面的代码控制台应用程序: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?

是INT的默认值是0您可以检查使用default关键字

int t = default(int); 

t将举行0

+0

+1谢谢 - 我认为这可能是这种情况,但它似乎有点违背语言的强类型安全基础 – whytheq

+0

类型安全的严格性?怎么来的 ? – Habib

+0

我真的没有正确表达它的意思......它看起来像一个非常严格的语言,但这种默认似乎违反严格? ...我有什么意义 – whytheq

没错。 int默认值是0

是的,zero是int的默认值。

在构造函数运行之前,类中的字段被初始化为默认值。 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