本帖最后由 指尖舞者 于 2014-8-9 22:47 编辑
习题: 写一个Ticket类,有一距离属性(本属性只读,在构造方法中赋值),不能为负数,有一个价格属性,价格属性只读,并且根据距离计算价格(1元/公里): 0-100公里 票价不打折 100-200 总额打9.5折 200-300 9折 300以上 8折 有一个方法,可以显示这张票的信息
下面代码错误:
- class Ticket
- {
- public Ticket(int distance)
- {
- this.distance = distance;
- }
- int distance;
- public int Distance
- {
- get { return distance; }
- }
- double price;
- public double Price
- {
- get
- {
- if (distance > 0)
- {
- if (distance <= 100)
- {
- price = distance * 1.0;
- }
- else if (distance <= 200)
- {
- price = distance * 0.95;
- }
- else if ( distance <= 300)
- {
- price = distance * 0.9;
- }
- else
- {
- price = distance * 0.8;
- }
- }
- else
- {
- price = 0;
- }
- return price;
- }
- }
- public void ShowPrice()
- {
- Console.WriteLine("你选择的票,行驶距离{0},票价为{1}",distance,price);
- }
- }
复制代码正确代码:
- class Ticket
- {
- public Ticket(int distance)
- {
- this.distance = distance;
- if (distance > 0)
- {
- if (distance <= 100)
- {
- this.price = distance * 1.0;
- }
- else if (distance <= 200)
- {
- this.price = distance * 0.95;
- }
- else if (distance <= 300)
- {
- this.price = distance * 0.9;
- }
- else
- {
- this.price = distance * 0.8;
- }
- }
- else
- {
- this.price = 0;
- }
- }
- int distance;
- public int Distance
- {
- get { return distance; }
- }
- double price;
- public double Price
- {
- get
- {
- return price;
- }
- }
- public void ShowPrice()
- {
- Console.WriteLine("你选择的票,行驶距离{0},票价为{1}",distance,price);
- }
- }
复制代码 两者的区别就在于:正确的是给if判断语句放到了构造方法中,错误的是放在了get中,为什么要放到构造方法中呢?
通过逐语句会发现 放到get中 直接不会执行if语句的
|