C#学习笔记-字段、属性、索引器

字段

  字段表示与对象或者类型(类或结构体)关联的变量(成员变量),为对象或类型存储数据。与对象关联的字段称为“实例字段”,隶属于某个对象。与类型关联的字段称为“静态字段”,表示某一个类型当前的状态。

  静态字段使用 static 关键字修饰。字段在没有显示初始化的情况下会获得其类型的默认值,静态字段在类型被加载时初始化,当一个数据类型被运行环境加载的时候,其静态构造器会被调用且只被调用一次。实例字段在对象创建是被初始化。

class Student
{
    static public int number; //静态字段

    private int id;           //实例字段
    private string name;
    private int age;

    public Student()          //实例构造器
    {
        name = "null";
    }

    static Student()          //静态构造器
    {
        number = 0;
    }
}

Console.WriteLine(Student.number);

 属性

  属性用于访问对象或类型的特征的类成员。属性大多数情况下是字段的包装器,由Get/Set方法对发展而来,实际上是一个语法糖。与字段不同的是,属性不表示存储位置。

  属性和字段一般情况下都用来表示实体(对象或类型)的状态,更好的选择是使用属性来供外界访问字段,字段使用 private 或 protected 修饰。

class Student
{
    private int age;  //字段

    public int Age    //属性
    {
        get { return this.age; }
        set
        {
            if(value < 0 || value > 120) {
                throw new Exception("Age value has Error!");
            }
            this.age = value;  //返回 age 而不是 Age,否则会造成栈溢出
        }
    }
    
    public int Score { get; set; } //属性的简略声明,功能上和公有字段一样,不受保护,一般用于传递数据
}

Student stu = new Student();
stu.Age = 20;
Console.WriteLine(stu.Age);

索引

  索引器使对象能够用和数组相同的方式(使用下标)进行索引。

class Student
{
    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 can't be null!");
            }
            if (this.scoreDictionary.ContainsKey(subject)){
                this.scoreDictionary[subject] = value.Value;
            }
            else
            {
                this.scoreDictionary.Add(subject, value.Value);
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Student stu = new Student();

        Console.WriteLine(stu["Math"]);

        stu["Math"] = 90;

        Console.WriteLine(stu["Math"]);
    }
}

常量

  成员常量是表示常量值的类成员,在编译时将常量标识符替换为对应的值,以提高程序运行时的效率。成员常量隶属于类型而不是对象,没有实例常量。“实例常量”的效果可以由只读字段来实现。“只读”的应用场景:

  1、提高程序可读性和执行效率--常量

  2、防止对象的值被改变--只读字段

  3、向外暴露不允许修改的值--只读属性(静态或非静态),静态只读属性和常量在功能上类似,但是编译器对二者的处理不同。

  4、希望成为常量的值其类型不能被常量声明接受时(类/自定义结构体)--静态只读字段

class Web
{
    public const Building Location = new Building() { Address = "Address"}; //invalid
    public static readonly Building Location = new Building() { Address = "Address" }; //valid
}

class Building
{
    public string Address {  get; set; }
}

 

posted @   owmt  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示