using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test2 { class Ticket { decimal distance; public decimal Price { get { if (distance > 0 && distance < 10) return 1.0m * distance; else if (distance >= 10 && distance < 20) return 0.9m * distance; else return 0.8m * distance; } } public decimal Distance { get { return distance; } set { if(distance <0) { throw new Exception("距离不能为负数"); } distance = value; } } public void ShowPrice() { Console.WriteLine("距离:{0} 票价:{1}", distance, Price); } public Ticket(decimal distance) { this.distance = distance; } public Ticket() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test2 { class Program { static void Main(string[] args) { Ticket t1 = new Ticket(9); t1.ShowPrice(); Ticket t2 = new Ticket(); t2.Distance = 10; t2.ShowPrice(); Console.ReadKey(); } } }