使用readonly修饰符可以将类的字段修饰为只读,该字段只能在初始化的时候被赋值
字段也可以叫
属性
用于访问对象或类型特征的成员,特征反应了状态

属性就是在字段之上发展而来的
在类里面定义这样的代码块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| private int age = 2222; public int Age { set { if(value>=0 && value <= 100) { this.age = value; } else { throw new Exception("请输入正确的年龄"); } } get { return this.age; } }
|
和Java相比,感觉像是把get和set方法变成了属性调用,而不是方法调用
编辑器输入propfull,然后两下tab键,可以快捷生成完整声明属性声明
prop生成简略声明
索引器
它使对象能够用与数组相同的方式(即使用下标)进行索引
get拿着索引名称,去字典里面查
个人感觉像json的键值对
这里使用集合来实现索引
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| private Dictionary<string, int> scoreDictionary = new Dictionary<string, int>(); public int? this[string subject] { get { if (this.scoreDictionary.ContainsKey(subject)) { return this.scoreDictionary[subject]; } else { return null; } } set { if (value.HasValue == false) { throw new Exception("Score cannot be null."); } if (this.scoreDictionary.ContainsKey(subject)) { this.scoreDictionary[subject] = value.Value; } else { this.scoreDictionary.Add(subject, value.Value); } } }
|
1 2 3 4 5 6 7
| main{ Student student = new Student(); student["Math"] = 90; var mathScore = student["Math"]; Console.WriteLine(mathScore); Console.ReadKey(); }
|