public sealed class classroom { private List<string> student = new List<string>(); private List<string> student1 = new List<string>(); public List<string> Student { get { return student; } set { student1 = value; } } // public List<string> Student = new List<string>(); private string name="xiaoming"; public string Name { get { return name; } // set { name = value; } } } static void Main(string[] args) { classroom students = new classroom { Student = { "a", "b" } }; foreach (var item in students.Student) { Console.WriteLine(item.ToString()); } students.Student = new List<string>() { "c"}; }
通过上面代码 验证:
get索引器 相当于 Student=student
即:Student 实际上是 对 student 指针的引用;操作 Student 实际上是 操作 student
用 Student.add()方法 修改对象时 不调用set方法。
set 索引器 相当于 student1=value
即: 当新建对象赋值给 student1是 会调用set方法。
相关文章: