一个int字段是否默认为0?

3

I have a Console app with the following code:

    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 时,是否一定要设置 Discount 属性。如果调用了 Discount 属性,那么变量 iGotChanged 应该返回 1 或 2,但它似乎仍然保持在 0。因为它的类型是整数 int,所以 payPerViewDiscount 是否有默认值为 0 呢?
4个回答

10

是的,int类型的默认值为0。您可以使用default关键字进行检查。

int t = default(int);

t将会存储0


+1 谢谢 - 我认为这可能是情况,但它似乎有点违背语言的强类型安全基础。 - whytheq
类型安全的严格性?为什么呢? - Habib
我没有表述得很准确...它似乎是一种非常严格的语言,但这个默认值似乎与这种严格性相反?... 我讲得通吗? - whytheq
默认情况下,分配相同类型的默认值,所以我认为这很好。通常情况下,在将其分配给某个值之前,您无法使用它,因为它是类中的字段,它将被分配“默认”值。 - Habib

4

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

感谢额外提供关于本地变量的说明 - 我猜以后我可能会为此苦恼。 - whytheq

2

没错,int 的默认值是 0


2

是的,0是int类型的默认值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接