using System; class Program { static void Main(string[] args) { Student student = new Student(); student.age = -10; Console.WriteLine(student.age);// 1 student.age = 10; Console.WriteLine(student.age);// 10 } } class Student { private int _age=1; public int age { get{ return _age; } set { if(value > 0 && value < 150) { _age = value; } } } public string name { get; private set; }//自动实现属性 }
方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
using System; class Program { static void Main(string[] args) { Student std = new Student(); std.Eat();//实例方法 Student.Study();//静态方法 } } class Student { public static void Study() { Console.WriteLine("I can study"); } public void Eat() { Console.WriteLine("I can eat"); } }
public class Student{ public const string School = "山河大学"; public readonly string Principal;//未初始化 public string name { get; set; } public int age { get; set; } public Student() { this.Principal = "刘校长"; } public Student(int age) { this.age = age; this.Principal = "高校长"; } }
class Program { static void Main(string[] args) { Student student = new Student(); student[0] = "学号:2002220115"; student[1] = "姓名:张三"; Console.WriteLine(student[0]); Console.WriteLine(student[3]); } } class Student { public string id; public string name; public string this[int i] { get { switch(i) { case 0:return id; case 1:return name; default: return "请在0-1中选择索引"; } } set { switch (i) { case 0: id = value;break; case 1: name = value;break; } } } }
索引器重载
只要索引器的参数列表不同(返回值不同是不够的),类就可以有多个索引器。
1 2 3 4 5 6 7 8 9 10
class Student{ public string this[int index]{ get{...} set{...} } public string this[int index1 , int index2]{ get{...} set{...} } }
partial class Student { public string id; public string name; public void study(int x);//定义分部方法 } partial class Student { public int age; public void study(int x){//实现分部方法 Console.WriteLine(x); } }