29常量成员
const 常量
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace yuan { class Program { static void Main(string[] args) { yuan y = new yuan(10); Console.WriteLine("圆周率{0}",yuan.pi); Console.WriteLine("半径{0}", y.r); Console.WriteLine("周长{0}", y.ZC()); Console.WriteLine("面积{0}", y.MJ()); } } class yuan { public int r; public const double pi = 3.1415926;//隐式的静态成员 public yuan(int rValue) { r = rValue; } public double ZC() { return 2 * pi * r; } public double MJ() { return pi * r * r; } } }
readonly 声明时可以不赋值。
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace zhidu { class Program { static void Main(string[] args) { Console.WriteLine("=====天空酒店====="); Hotel skyHotel = new Hotel(140); for (int i = 0; i < 141; i++) { skyHotel.LodgeIn(); } Console.WriteLine("房间总数{0}",skyHotel.roomNumber); Console.WriteLine("客人总数{0}", skyHotel.guestNumber); Console.WriteLine("=====天空2号酒店====="); Hotel skyHotel2 = new Hotel(180); for (int i = 0; i < 141; i++) { skyHotel2.LodgeIn(); } Console.WriteLine("房间总数{0}", skyHotel2.roomNumber); Console.WriteLine("客人总数{0}", skyHotel2.guestNumber); } class Hotel { public readonly int roomNumber; public int guestNumber = 0; public Hotel(int roomNumberValue) { roomNumber = roomNumberValue; } public bool isFull() { if (guestNumber >= roomNumber) return true; else return false; } public void LodgeIn() { if (isFull() == true) Console.WriteLine("对不起不能入住,房间已满!"); else { guestNumber++; Console.WriteLine("入住成功。"); } } } } }

浙公网安备 33010602011771号