• 【C# Programming】类、构造器、静态成员


    一、类

    1、类的概念

    • 类是现实世界概念的抽象:封装、继承、多态
    • 数据成员: 类中存储数据的变量
    • 成员方法: 类中操纵数据成员的函数称为成员方法
    • 对象:类的实例
    • 类定义
    1. class X {…}      
    2. var instance = new X(…);

    2、实例字段

            C#中,数据成员称为字段。与具体对象相关的字段称为实例字段;实例字段允许在声明时初始化,初始化语句在类构造函数前执行, 例如:

    1. class Employee
    2. {
    3. public string FirstName;
    4. public string LastName;
    5. public string Salary = "Not enough";
    6. public Employee()
    7. {
    8. Salray= string.Empty;
    9. }
    10. }

            实例字段只能从对象中访问,例如:

    1. public static void Main()
    2. {
    3. Employee employee1 = new Employee();
    4. Employee employee2;
    5. employee2 = new Employee();
    6. employee1.FirstName = "Inigo";
    7. employee1.LastName = "Montoya";
    8. employee1.Salary = "Too Little";
    9. IncreaseSalary(employee1);
    10. Console.WriteLine( "{0} {1}: {2}",employee1.FirstName, employee1.LastName,employee1.Salary);
    11. }
    12. static void IncreaseSalary(Employee employee)
    13. {
    14. employee.Salary = "Enough to survive on";
    15. }

            C#中,  只能通过对象调用的成员方法称为实例方法。

            在类的实例成员内部,可以使用this 获得调用实例成员的对象引用,例如:

    1. class Employee
    2. {
    3. public string FirstName;
    4. public string LastName;
    5. public string Salary;
    6. public string GetName()
    7. {
    8. return $"{ FirstName } { LastName }";
    9. }
    10. public void SetName(string newFirstName, string newLastName)
    11. {
    12. this.FirstName = newFirstName;
    13. this.LastName = newLastName;
    14. }
    15. }

            this关键字也能用来显式调用实例方法 或在方法调用中传递 ,例如:

    1. class Employee
    2. {
    3. public string FirstName;
    4. public string LastName;
    5. public string Salary;
    6. public string GetName() => $"{ FirstName } { LastName }";
    7. public void SetName(string newFirstName, string newLastName)
    8. {
    9. this.FirstName = newFirstName;
    10. this.LastName = newLastName;
    11. Console.WriteLine( $"Name changed to '{ this.GetName() }'");
    12. }
    13. public void Save()
    14. {
    15. DataStorage.Store(this);
    16. }
    17. }
    18. class DataStorage
    19. {
    20. // Save an employee object to a file named with the Employee name.
    21. public static void Store(Employee employee) { ...}
    22. }

    3、访问修饰符

    访问修饰符标识了所修饰成员的封装级别。

    • public:类或成员修饰符;表明类或成员可以从类外部访问
    • private:成员修饰符; 表明修饰的成员仅在声明的类内部访问
    • protected:成员修饰符; 表明修饰的成员仅在声明的类或派生类内部访问
    • internal:类或成员修饰符;表明类或成员仅能在相同程序集内部访问
    • Protected internal:类或成员修饰符;表明类或成员仅能在当前程序集内部或派生类访问
    1. class Employee
    2. {
    3. public string FirstName, LastName,Salary, Password;
    4. private bool IsAuthenticated;
    5. public bool Logon(string password)
    6. {
    7. if (Password == password)
    8. IsAuthenticated = true;
    9. return IsAuthenticated;
    10. }
    11. public bool GetIsAuthenticated() => IsAuthenticated;
    12. // ...
    13. }

    4、方法的参数

            类型缺省访问级别:

    Members ofDefault member accessibilityAllowed declared accessibility of the member
    enumpublicNone
    classprivate

    public

    protected

    internal

    private

    protected internal

    interfacepublicNone
    structprivate

    public

    internal

    private

    5、属性

            属性结合了字段和成员方法的特点。 对于对象的用户来说,属性似乎是一个字段,访问属性使用与访问字段 相同的语法。 对于类的实现者来说,属性是由 get 访问器和/或 set 访问器组成代码块。读取属性时,执行 get 访问器的代码块;向属性赋值时,执行 set 访问器的代码块。

            不含 set 访问器的属性称为只读属性。 将不含 get 访问器的属性称为只写属性。同时具有以上两个访问器的属性称为读写属性。  

            与字段不同,属性不会被归类为变量。 因此,不能将属性作为 ref 或 out 参数传递。

    6、自动实现属性

            在 C# 3.0及更高版本,当属性访问器中不需要任何其他逻辑时,自动实现的属性会使属性声明更加简洁。在 C# 6和更高版本中,可以像字段一样初始化自动实现属性。

    1. public static void Main()
    2. {
    3. Employee employee1 = new Employee();
    4. Employee employee2 = new Employee();
    5. employee1.FirstName = "Inigo"; // Call the FirstName property's setter.
    6. System.Console.WriteLine(employee1.FirstName); // Call the FirstName property's getter.
    7. // Assign an auto-implemented property
    8. employee2.Title = "Computer Nerd";
    9. employee1.Manager = employee2;
    10. // Print employee1's manager's title.
    11. System.Console.WriteLine(employee1.Manager.Title);
    12. }
    13. class Employee
    14. {
    15. public string FirstName { get; set; }
    16. private string LastName { get; set; }
    17. public string Title { get; set; }
    18. public Employee Manager { get; set; }
    19. public string Salary { get; set; } = "Not Enough";
    20. }

    7、属性的访问限制

            缺省情况下,get /set 访问器具有相同的可见性和访问级别。从C# 2.0开始,在属性实现中允许为get 或set 部分指定访问修饰符,从而覆盖为属性指定的访问修饰符

            对属性 使用访问修饰符有以下限制:

    • 不能对接口或显式实现的接口成员使用访问修饰符。
    • 仅当属性同时包含 set 和 get 访问器时,才能使用访问器修饰符。 这种情况下,只允许对其中之一使用修饰符。
    • 如果属性或索引器具有 override 修饰符,则访问器修饰符必须与重载的访问器的访问修饰符(如有)匹配。
    • 访问器的可访问性级别必须比属性本身的可访问性级别具有更严格的限制。
    1. class Employee
    2. {
    3. public void Initialize(int id) => Id = id.ToString();
    4. public string Id
    5. {
    6. get
    7. {
    8. return _Id;
    9. }
    10. private set
    11. {
    12. // Providing an access modifier is possible in C# 2.0 and higher only
    13. _Id = value;
    14. }
    15. }
    16. private string _Id;
    17. }

    二、构造器

    1、构造器

    1.1 构造器是与类名相同,没有返回值的方法, 例如:
    1. class Employee
    2. {
    3. public Employee(string firstName, string lastName) // constructor
    4. {
    5. FirstName = firstName;
    6. LastName = lastName;
    7. }
    8. public string FirstName { get; set; }
    9. public string LastName { get; set; }
    10. public string Title {get; set}
    11. public string Salary { get; set; } = "Not Enough";
    12. public string Name
    13. {
    14. get
    15. {
    16. return FirstName + " " + LastName;
    17. }
    18. set
    19. {
    20. string[] names;
    21. names = value.Split(new char[] { ' ' });
    22. if (names.Length == 2)
    23. {
    24. FirstName = names[0];
    25. LastName = names[1];
    26. }
    27. else
    28. {
    29. throw new System.ArgumentException(string.Format($"Assigned value '{ value }' is invalid", nameof(value)));
    30. }
    31. }
    32. }
    33. }
    1.2 调用构造器
    1. public static void Main()
    2. {
    3. Employee employee;
    4. employee = new Employee("Inigo", "Montoya");
    5. employee.Salary = "Too Little";
    6. Console.WriteLine( "{0} {1}: {2}", employee.FirstName,
    7. employee.LastName,employee.Salary);
    8. }
    1.3 默认构造器

            如果类没有显式定义构造器,C# 编译器会在编译时自动添加一个不含任何参数的构造函数。一旦类显定义构造器,编译器就不会提供默认构造函数

    2、对象初始化器

            初始化器用于初始化对象中所有可以访问的字段和属性。在调用构造器时,可以在后面的大括号中添加成员初始化列表,例如:

    1. public static void Main()
    2. {
    3. Employee employee = new Employee("Inigo", "Montoya")
    4. {
    5. Title = "Computer Nerd",
    6. Salary = "Not enough"
    7. };
    8. Console.WriteLine("{0} {1} ({2}): {3}", employee.FirstName, employee.LastName, employee.Title, employee.Salary);
    9. }

    3、构造器链

            C# 中,允许从一个构造器中调用同一个类的另一个构造器, 方法是在一个冒号后添加this关键字,再添加被调用构造器的参数列表,例如:

    1. class Employee
    2. {
    3. public Employee(string firstName, string lastName)
    4. {
    5. FirstName = firstName;
    6. LastName = lastName;
    7. }
    8. public Employee(int id, string firstName, string lastName)
    9. : this(firstName, lastName)
    10. {
    11. Id = id;
    12. }
    13. public Employee(int id)
    14. {
    15. Id = id;
    16. // NOTE: Member constructors cannot be called explicitly inline
    17. // this(id, firstName, lastName);
    18. }
    19. public int Id { get; private set; }
    20. public string FirstName { get; set; }
    21. public string LastName { get; set; }
    22. public string Salary { get; set; } = "Not Enough";
    23. }

    4、匿名类型

            匿名类型是编译器动态生成的类型,编译器遇到匿名类型时,会自动生成一个CIL类。该类具有与匿名类型声明中已经命名的值和数据类型对应的属性。例如:

    1. public static void Main()
    2. {
    3. var patent1 =new
    4. {
    5. Title = "Bifocals",
    6. YearOfPublication = "1784"
    7. };
    8. var patent2 =new
    9. {
    10. Title = "Phonograph",
    11. YearOfPublication = "1877"
    12. };
    13. var patent3 =new
    14. {
    15. patent1.Title,
    16. Year = patent1.YearOfPublication
    17. };
    18. System.Console.WriteLine("{0} ({1})",patent1.Title, patent1.YearOfPublication);
    19. System.Console.WriteLine("{0} ({1})", patent2.Title, patent1.YearOfPublication);
    20. Console.WriteLine();
    21. Console.WriteLine(patent1);
    22. Console.WriteLine(patent2);
    23. Console.WriteLine();
    24. Console.WriteLine(patent3);
    25. }

    三、静态成员

    1、静态字段

            在类的多个实例之间共享的字段,用static 关键字标识。和实例字段一样,静态字段也可以在声明时初始化。例如:

    1. class Employee
    2. {
    3. // ...
    4. public static int Id; // default(int): 0
    5. public static int NextId = 42;
    6. // ...
    7. }

            和实例字段不一样,未初始化的静态字段将获得默认值,即 default(T)的结果

    2、静态方法

            和静态字段类似,静态方法也用static关键字标识。静态方法可以通过类名直接访问。例如:

    1. public static void Main()
    2. {
    3. DirectoryInfo directory = new DirectoryInfo(".\\Source");
    4. directory.MoveTo(".\\Root");
    5. DirectoryInfoExtension.CopyTo(directory, ".\\Target", SearchOption.AllDirectories, "*");
    6. }
    7. public static class DirectoryInfoExtension
    8. {
    9. public static void CopyTo( DirectoryInfo sourceDirectory, string target, SearchOption option, string searchPattern)
    10. {
    11. if (target[target.Length - 1] != Path.DirectorySeparatorChar)
    12. target += Path.DirectorySeparatorChar;
    13. if (!Directory.Exists(target))
    14. Directory.CreateDirectory(target);
    15. for (int i = 0; i < searchPattern.Length; i++)
    16. {
    17. foreach (string file in Directory.GetFiles(sourceDirectory.FullName, searchPattern))
    18. {
    19. File.Copy(file, target + Path.GetFileName(file), true);
    20. }
    21. }
    22. if (option == SearchOption.AllDirectories) //Copy subdirectories (recursively)
    23. {
    24. foreach (string element in Directory.GetDirectories(sourceDirectory.FullName))
    25. Copy(element, target + Path.GetFileName(element),searchPattern);
    26. }
    27. }
    28. private static void Copy(string element, string fileName, string searchPattern)
    29. {
    30. Console.WriteLine("Copying " + fileName);
    31. }
    32. }

    3、静态构造器

            静态构造器不显式调用,而是在运行时在首次访问类时自动调用。首次访问类发生在条用普通构造器时,也可能发生在访问类的静态方法或字段。静态构造器不允许带任何参数

    1. class Employee
    2. {
    3. static Employee()
    4. {
    5. Random randomGenerator = new Random();
    6. NextId = randomGenerator.Next(101, 999);
    7. }
    8. // ...
    9. public static int NextId = 42;
    10. // ...
    11. }

    4、静态属性

            属性也能static。例如:

    1. class Employee
    2. {
    3. // ...
    4. public static int NextId
    5. {
    6. get
    7. {
    8. return _NextId;
    9. }
    10. private set
    11. {
    12. _NextId = value;
    13. }
    14. }
    15. public static int _NextId = 42;
    16. // ...
    17. }

    5、静态类

            C#中也能定义静态类。静态类不含任何实例字段或方法。因此静态类不能实例化。编译器自动在CIL 代码中将静态类标记为abstract 和sealed。即将类指定为不可扩展

    1. public static class SimpleMath
    2. {
    3. public static int Max(params int[] numbers)
    4. {
    5. if (numbers.Length == 0) // Check that there is at least one item in numbers.
    6. throw new ArgumentException( "numbers cannot be empty", nameof(numbers));
    7. int result = numbers[0];
    8. foreach (int number in numbers)
    9. {
    10. if (number > result)
    11. result = number;
    12. }
    13. return result;
    14. }
    15. }
    16. public class Program
    17. {
    18. public static void Main(string[] args)
    19. {
    20. int[] numbers = new int[args.Length];
    21. for (int count = 0; count < args.Length; count++)
    22. numbers[count] = args[count].Length;
    23. Console.WriteLine( $@"Longest argument length = { SimpleMath.Max(numbers) }");
    24. }
    25. }

    6、封装数据

    6.1 const 字段
    • const 字段是在编译时确定的值, 在运行时不会被改变。常量字段自动成为静态字段  
    • 如果一个程序集引用了另一个程序集中的常量,常量值将直接编译进引用的程序集中
    1. class ConvertUnits
    2. {
    3. public const float CentimersPerInch = 2.54F;
    4. public const int CupsPerGallon = 16;
    5. }
    6.2 readonly

            readonly 修饰符只能用于字段(不能用于局部变量)。它指出字段值只能从构造器中更改或声明时通过初始化器更改。

    1. class Employee
    2. {
    3. public Employee(int id)
    4. {
    5. _Id = id;
    6. }
    7. private readonly int _Id;
    8. public int Id{
    9. get { return _Id; }
    10. }
    11. // Error: A readonly field cannot be assigned to (excep in a constructor or a variable initializer)
    12. // public void SetId(int id) =>_Id = id;
    13. }

    7、分部类

            分部类是一个类的多个部分, 这些部分可以合并成一个完整的类。分部类主要用于将一个类的定义划分到多个文件中。 C# 使用关键字partial来声明分部类

    1. // File: Program1.cs
    2. partial class Program
    3. {
    4. }
    5. // File: Program2.cs
    6. partial class Program
    7. {
    8. }

    8、分部方法

            分部方法存在于分部类中,它允许在一个文件中声明方法,而在另一文件中实现该方法。例如:

    1. // File: Person.Designer.cs
    2. public partial class Person
    3. {
    4. #region Extensibility Method Definitions
    5. partial void OnLastNameChanging(string value);
    6. partial void OnFirstNameChanging(string value);
    7. #endregion
    8. // ...
    9. }
    10. // File: Person.cs
    11. partial class Person
    12. {
    13. partial void OnLastNameChanging(string value)
    14. {
    15. //...
    16. }
    17. partial void OnFirstNameChanging(string value)
    18. {
    19. //...
    20. }
    21. }
  • 相关阅读:
    入侵检测技术
    linux 系统文件目录颜色及特殊权限对应的颜色
    AI应用开发:pgvector能帮你解决什么问题
    “图片在哪”、“我是temunx”、“变成思维导图用xmindparser”gpt给出文本变字典
    挂脖式运动蓝牙耳机推荐,目前适合运动佩戴的五款耳机推荐
    Aop天花板
    基于JAVA-英杰学堂网上教学平台-计算机毕业设计源码+系统+mysql数据库+lw文档+部署
    “2024杭州国际物联网展览会”定于4月份在杭州国际博览中心召开
    Django学习(1)Model
    基于神经网络的预测模型控制器matlab仿真
  • 原文地址:https://blog.csdn.net/weixin_44906102/article/details/132725560