** **
常量 与类关联的常量值
字段 类的变量
方法 类可执行的计算和操作
属性 与读写类的命名属性相关联的操作
索引器 与以数组方式索引类的实例相关联的操作
事件 可由类生成的通知
运算符 类所支持的转换和表达式运算符
构造函数 初始化类的实例或类本身所需的操作
析构函数 在永久丢弃类的实例之前执行的操作
类型 类所声明的嵌套类型

总结:整个都是字段,属性是字段的包装器,索引器是数组类型字段的包装器,常量是定值的字段、

字段 field

字段 (field) 是一种表示与对象或类关联的变量的成员。field-declaration 用于引入一个或多个给定类型的字段。
字段命名规则为:名词+首字母大写
image.png

提醒:局部变量和局部常量适用范围是方法体

image.png

image.png

字段和静态字段

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. List<Student> stuList = new List<Student>();
  6. for (int i = 0; i < 100; i++)
  7. {
  8. Student stu = new Student();
  9. stu.Score = 100-i;
  10. stu.Name = "wangming";
  11. stu.Age = 22;
  12. stuList.Add(stu);
  13. }
  14. double totalScore = 0;
  15. int totalAge = 0;
  16. foreach (var stu in stuList)
  17. {
  18. totalAge += stu.Age;
  19. totalScore += stu.Score;
  20. }
  21. Student.AverageAge = totalAge / Student.Amount;
  22. Student.AverageScore = totalScore / Student.Amount;
  23. Student.ReportAmount();
  24. Student.ReportAverageAge();
  25. Student.ReportAverageScore();
  26. }
  27. }
  28. class Student {
  29. public int Age;
  30. public string Name;
  31. public double Score;
  32. public static int Amount;
  33. public static double AverageAge;
  34. public static double AverageScore;
  35. public Student()
  36. {
  37. Amount++;
  38. }
  39. public static void ReportAmount()
  40. {
  41. Console.WriteLine(Amount);
  42. }
  43. public static void ReportAverageAge()
  44. {
  45. Console.WriteLine(Student.AverageAge);
  46. }
  47. public static void ReportAverageScore()
  48. {
  49. Console.WriteLine(Student.AverageScore);
  50. }

image.png
image.png
静态构造器先被调用且仅调用一次,实例构造器后调用且每次声明新实例都将调用。

readonly

实例只读字段

  1. 声明时赋值

image.png
image.png
image.png
静态只读字段

  1. 静态构造函数中设置值
  2. 声明时设置值

    class Program
     {
         static void Main(string[] args)
         {
             Console.WriteLine(Brush.DefultColor.Red);
             Console.WriteLine(Brush.DefultColor.Blue);
             Console.WriteLine(Brush.DefultColor.Green);
         }
     }
     struct Color
     {
         public int Red;
         public int Green;
         public int Blue;
    
     }
     class Brush
     {
         public static readonly Color DefultColor;
         //   public static readonly Color DefultColor = new Color() { Red = 0, Green = 0, Blue = 0 };
         static Brush()
         {
             DefultColor = new Color() { Red = 0, Green = 0, Blue = 0 };
         }
    

    结构体 struct

  3. 用户定义的数据类型

  4. 赋值和访问

    class Program
     {
         static void Main(string[] args)
         {
            Student stu1=new Student();
             stu1.Age = 20;
             stu1.Id= 1;
             stu1.Name = "Ma";
    
             Student stu2 = new Student();
             stu2 = stu1;    //赋值
             stu2.Id = 2;
             stu2.Name = "Zhao";
             Console.WriteLine("学号{0},姓名{1},年龄{2}",stu2.Id,stu2.Name,stu2.Age); //访问
         }
     }
    struct Student
     {
         public int Id;
         public string Name;
         public int Age;
    
     }
    

    属性 property

    属性 (property) 是一种用于访问对象或类的特征的成员
    本质是字段,通过方法来实现其功能
    image.png

属性与方法:

       public int Age
        {
            get { return age = 20; }
            set {
                if (value < 0 || value > 120)
                {
                    throw new Exception("Age has an error!");
                }
                else
                {
                    this.age = value;
                }

            }
        }

        public void SetAge(int value)
        {
            if (value < 0 || value > 120)
            {
                throw new Exception("Age has an error!");
            }
            else
            {
                this.age = value;
            }
        }
        public int GetAge()
        {
            return this.age;
        }

完整声明和简略声明

简略声明只用来传递数据,因为和公有字段一样,容易污染

propfull

image.png

prop

image.png

编辑-重构-封装字段

image.png

只读属性与内部写属性

image.png

动态计算属性

非经常使用canwork属性
image.png
如果经常判断canwork属性用下面的

  public int Age
        {
            get { return age = 20; }
            set
            {
                if (value < 0 || value > 120)
                {
                    throw new Exception("Age has an error!");
                }
                else
                {
                    this.age = value;
                    this.CaculateCanWork();
                }

            }
        }
        private bool canWork;
        public bool CanWork
        {
            get {

                return this.canWork; }

        }
        public void CaculateCanWork()
        {
            if (this.age >= 16)
            {
                this.canWork = true;
            }
            else this.canWork = false;
        }

索引器indexer

使对象能够用与数组相同的方式进行索引.

  • 一般为集合类型,也有非集合类型
  • 对于字段为数组类型,用索引来防止污染
  • 访问形式为 实例名[实参]
  • 必须为实例的

image.png

this 用法:

  1. 实例构造函数中使用
  2. 将当前对象作为参数传递到其他方法中
  3. 声明索引器
 class Employee
    {
        private string name;
        private decimal salary;

        public Employee(string name,decimal salary)
        {
            this.name = name;
            this.salary = salary; //用法一:此salary非彼salary
        }
        public decimal Salary
        {
            get { return this.salary; }

        }
        public void PrintEmployee()
        {
            Console.WriteLine("Name:{0}", this.name);
            Console.WriteLine("Tax:{0}", Tax.CaclulateTax(this));//用法二:对象做参数
        }

    }

    class Tax
    {
        public static decimal CaclulateTax(Employee em)
        {
            if (em.Salary <= 5000)
            {
                return 0;
            }
            else
            {
                return (em.Salary - 5000) * 0.25m;
            }
        }
    }

索引器集合实现

         Student stu = new Student();
            Console.WriteLine(stu[0]);
            stu[0] = 10;
            stu[1] = 20;         
            Console.WriteLine(stu[0]);
            Console.WriteLine(stu[1]);


private int[] score = new int[3];

       public int? this[int n]
        {
            get {
                return this.score[n];
                /* return the specified index here */ }
            set {
                if (value.HasValue==false)
                {
                    throw new Exception("值不能为空!");
                }
                if (value.Value>100)
                {
                    this.score[n] = 100;
                }
                else if(value.Value<0)
                {
                    this.score[n] = 0;
                }
                else
                {
                    this.score[n] = value.Value;
                }
                /* set the specified index to value here */ }
        }

索引器的非集合实现

  class Program
    {
        static void Main(string[] args)
        {
            Student stu1 = new Student();
            stu1["math"] = 90;
            stu1["math"] = 100;
            stu1["English"] = 89;
            var mathScore = stu1["math"];
            var engScore = stu1["English"];
            Console.WriteLine(mathScore);
            Console.WriteLine(engScore);

        }
    }
   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 -1;
                }
                /* return the specified index here */ }
            set {
                if (value.HasValue==false)
                {
                    throw new Exception("值不能为空!");
                }
                if (this.scoreDictionary.ContainsKey(subject))
                {
                    this.scoreDictionary[subject] = value.Value;
                }
                else
                {
                    this.scoreDictionary.Add(subject, value.Value);
                }
                /* set the specified index to value here */ }
        }
    }

常量 const

  • 隶属于类型
  • 编译时直接用值代替

image.png

 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Student.sex);
            Console.WriteLine(Student.website);
        }
    }
    class Student
    {
        public const string sex= "female";
        public const string website = "http://ONE-Piece.cn";
    }