Perform some simple verification on the property, and verify the property.
When developing a C # program and writing it to the property, we can perform some simple rule verification in the Set Method:
As shown in the following figure, Insus. NET writes an Age attribute, allowing users to enter only numbers less than 10:
Class AA {private int _ Age; public int Age {get {return _ Age;} set {if (value> 10) {throw new Exception ("only children under 10 years old are allowed to participate. ") ;}_ Age = value ;}} Source Code
Front-end, we just use try... catch... to throw an exception:
Console. write ("Enter your age:"); AA obj = new AA (); obj. age = Convert. toInt32 (Console. readLine (); try {Console. writeLine ("your age is:" + obj. age);} catch (Exception ex) {Console. writeLine (ex. message);} Source Code
Press Ctrl + F5:
Enter a number smaller than 10, for example, 7, and press Enter:
Press Ctrl + F5 again and enter a number greater than 10, for example, 11. The console displays the following: