简体   繁体   中英

Write only accessors in C#

How do the so called write only accessors works, for instance 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;
    }
}

When I write

CableBill january = new CableBill(4);
MessageBox.Show(january.CalculateAmount(7).ToString());

The return value is 28

My question is:
How does the program know that payPerViewDiscount=0 ?I never used the Discount property when I initialized my object

All members of a class are automatically initialized with the default value of their type. For an int this is 0 .

By the way, write-only properties are bad style (according to Microsoft's design guidelines ). You should probably use a method instead.

If you didn't initialize an int , its default value will be equal to 0

int myInt = new int();

The preceding statement has the same effect as the following statement:

int myInt = 0;

Default Values Table

In c# you can use the default keyword to determine default values of types.

For example:

default(bool)
default(int)
default(int?)

All the primitive types like

int, double, long etc

are assigned default value automatically.

default value for int=0;
default value for char='\0';
default value for char='\0';

Forexample you don't know default value of some primitive type you can access them like this

 public void PassDefaultValues(bool defaultBool, DateTime defaultDateTime)
 {
   // Nothing
 }

and you can call it like this

        public void PassDefaultValues(default(bool), default(DateTime));

It is because default bool is set to false , and then if goes the route of setting internal this.discount to be false, makes a check and goes into else which sets payPerViewDiscount to 0. One should always call write only accessors in constructor by setting the default value.

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

You should be setting default to this.Default and not to underlying property.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM