首页 > 编程语言 > 详细

C#语言入门(9)字段,属性,索引器,常量

时间:2021-07-31 22:14:46      阅读:27      评论:0      收藏:0      [点我收藏+]

技术分享图片

1、字段

(1)什么是字段

  • 字段( field)是一种表示与对象或类型(类与结构体)关联的变量
  • 字段是类型的成员,旧称”成员变量”
  • 与对象关联的字段亦称"实例字段”
  • 与类型关联的字段称为”静态字段",由static修饰
    ```c#
    namespace ConsoleApp2
    {
    class Program
    {
    static void Main(string[] args)
    {

        List<Student> stuList = new List<Student>();
        for (int i = 0; i < 100; i++)
        {
            Student stu = new Student();
            stu.Age = 24;
            stu.Score = i;
            stuList.Add(stu);
        }
        int totalAge = 0;
        int totalScore = 0;
        foreach (var stu in stuList)
        {
            totalAge += stu.Age;
            totalScore += stu.Score;
        }
        Student.AverageAge = totalAge / Student.Amount;
        Student.AverageScore = totalScore / Student.Amount;
        Student.ReportAmount();
        Student.ReportAverageAge();
        Student.ReportAveragSecore();
    
    }

    }

    class Student
    {
    public int Age;
    public int Score;
    public static int AverageAge;
    public static int AverageScore;
    public static int Amount;

    public Student()
    {
        Student.Amount++;
    }
    public static void ReportAmount()
    {
        Console.WriteLine(Student.Amount);
    }
    public static void ReportAverageAge()
    {
        Console.WriteLine(Student.AverageAge);
    }
    public static void ReportAveragSecore()
    {
        Console.WriteLine(Student.AverageScore);
    }

    }
    }

(2)字段的声明

  • 参见C#语言定义文档(一定要定义在类体力,不要定义在函数体里)
  • 尽管字段声明带有分号,但它不是语句
  • 字段的名字一定是名词

(2)字段的初始值

  • 无显式初始化时,字段获得其类型的默认值,所以字段"永远都不会未被初始化”
  • 实例字段初始化的时机————对象 创建时
  • 静态字段初始化的时机————类型被加载(load)时

    (2)只读字段(readonly)

  • 实例只读字段
    ```c#
    namespace ConsoleApp2
    {
    class Program
    {
    static void Main(string[] args)
    {
    Student stu1 = new Student(1);
    Console.WriteLine(stu1.ID);
    }
    }

    class Student
    {
    public readonly int ID;
    public int Age;
    public int Score;
    public Student(int id)
    {
    this.ID = id;
    }
    public static int AverageAge;
    public static int AverageScore;
    public static int Amount;

    }
    }

  • 静态只读字段
    ```c#
    namespace ConsoleApp2
    {
    class Program
    {
    static void Main(string[] args)
    {
    Console.WriteLine(Brush.DefaultColor.Red);
    Console.WriteLine(Brush.DefaultColor.Green);
    Console.WriteLine(Brush.DefaultColor.Blue);
    }
    }

    class Color
    {
    public int Red;
    public int Green;
    public int Blue;
    }
    class Brush
    {
    public static readonly Color DefaultColor = new Color() { Red = 0,Green = 0,Blue = 0 };
    }
    }

    
    ## 2、属性
    ### (1)什么是属性
  • 属性(property)是一种用于访问对象或类型的特征的成员,特征反映了状态
  • 属性是字段的自然扩展
    • 从命名上看, field更偏向于实例对象在内存中的布局, property更偏向于反映现实世界对象的特征
    • 对外:暴露数据,数据可以是存储在字段里的,也可以是动态计算出来的
    • 对内:保护字段不被非法值”污染"
  • 属性由Get/Set方法对进化而来
  • 又一个“语法糖”——属性背后的秘密

    (2) 属性的声明(propfull+Tab)

  • 完整声明——后台(back)成员变量与访问器(注意使用code snippet和refactor工具)
  • 简略声明——只有访问器(查看IL代码)
  • 动态计算值的属性
  • 注意实例属性和静态属性
  • 属性的名字一定是名词
  • 只读属性——只有getter没有setter

    • 尽管语法上正确,几乎没有人使用"只写属性”,因为属性的主要目的是通过向外暴露数据而表示对象/类型的状态
      ```c#
      namespace ConsoleApp2
      {
      class Program
      {
      static void Main(string[] args)
      {
      try
      {
      Student.Amount = -100;
      Console.WriteLine(Student.Amount);
      }
      catch (Exception ex)
      {
      Console.WriteLine(ex.Message);
      }
      }

    }

    private static int amount;
    
    public static int Amount
    {
        get { return amount; }
        set {
            if (value>=0)
            {
                Student.amount = value;
            }
            else
            {
                throw new Exception("Amount must greater than 0.");
            }
           }
    }

    }

}


### (3) 属性与字段的关系
- 一般情况下,它们都用于表示实体(对象或类型)的状态
- 属性大多数情况下是字段的包装器(wrapper)
- 建议:永远使用属性(而不是字段)来暴露数据,即字段永远都是private或protected的
## 3、索引器
### (1)什么是索引器
- 索引器(indexer)是这样一种成员 :它使对象能够用与数组相同的方式(即使用下标)进行索引
### (2)索弓器的声明(indexer+Tab)
- 参见C#语言定义文档
- 注意:没有静态索引器

```c#
namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student();
            stu["Math"] = 90;
            stu["Math"] = 100;
            var mathScore = stu["Math"];
            Console.WriteLine(mathScore);
        }

    }

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

    }

}

4、常量

(1)什么是常量

  • 常量(constant)是表示常量值(即,可以在编译时计算的值)的类成员
  • 常量隶属于类型而不是对象,即没有"实例常量”
    • “实例常量"的角色由只读实例字段来担当
  • 注意区分成员常量与局部常量

    (2)常量的声明

    (3)各种"只读”的应用场景

  • 为了提高程序可读性和执行效率——常量
  • 为了防止对象的值被改变——只读字段
  • 向外暴露不允许修改的数据——只读属性(静态或非静态),功能与常量有一些重叠
  • 当希望成为常量的值其类型不能被常量声明接受时(类/自定义结构体)——静态只读字段

C#语言入门(9)字段,属性,索引器,常量

原文:https://blog.51cto.com/u_15296868/3241834

(0)
(0)
   
举报
评论 一句话评论(0
分享档案
最新文章
教程昨日排行
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!