在C#中只写访问器

bao*_*ozi 1 c#

例如,所谓的只写访问器如何工作 Discount

class CableBill
{
    private int rentalFee;
    private int payPerViewDiscount;
    private bool discount;

    public CableBill(int rentalFee)
    {
        this.rentalFee = rentalFee;
        discount = false;
    }

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

    public int CalculateAmount(int payPerViewMoviesOrdered)
    {
        return (rentalFee - payPerViewDiscount) * payPerViewMoviesOrdered;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我写作

CableBill january = new CableBill(4);
MessageBox.Show(january.CalculateAmount(7).ToString());
Run Code Online (Sandbox Code Playgroud)

返回值是28

我的问题是:
程序是如何知道的payPerViewDiscount=0Discount我初始化对象时从未使用过该属性

Seb*_*zus 6

类的所有成员都会使用default其类型的值自动初始化.对于int这是0.

顺便说一句,只写属性是坏的风格(根据微软的设计指南).你可能应该使用一种方法.

  • 只写属性只有坏风格才有副作用.我同意你的回答,但不得不同意这个前提:) (2认同)