using System; using System.Collections.Generic; using System.Text; //p194 //使用字段方法和属性 namespace ConsoleApplication1 { class MyClass { public readonly string Name; public int intVal; public int Val { get { return intVal; } set { if (value >= 0 && value <= 10) intVal = value; else throw (new ArgumentOutOfRangeException("val", value, "Val must be assign a value between 0 and 10.")); } } public override string ToString() { return "Name:" + Name + "/nVal:" + Val; } private MyClass():this("Default Name") { } public MyClass(string newName) { Name = newName; intVal = 0; } static void Main(string[] args) { Console.WriteLine("Creating object myObj..."); MyClass myObj = new MyClass("My Object"); Console.WriteLine("myObj created"); for (int i = -1; i <= 0; i++) { try { Console.WriteLine("/nAttempting to assign {0} to myObj.Val...", i); myObj.Val = i; Console.WriteLine("value{0} assigned to myObj.val.", myObj.Val); } catch (Exception e) // i不在0~10之间时出错,这个错误传给e { Console.WriteLine("exception {0} thrown.", e.GetType().FullName); Console.WriteLine("Message:/n/"{0}/"", e.Message); } } Console.WriteLine("/nOutputting myObj.ToString()..."); Console.WriteLine(myObj.ToString()); Console.WriteLine("myobj.tostring() output."); } } }
|