C# 学习笔记 - 2.3 - 对象

发布时间 2023-08-21 20:31:17作者: Snoopy1866

对象

介绍

.NET Framework 遵循“面向对象程序设计(object orientated programming, OOP)”的软件开发方法,在该标准下,所有对象都支持:

  • 继承(Inheritance): 继承和拓展现有功能
  • 封装(Encapsulation): 允许用户查看特定部分,并通过特定访视与之交互
  • 多态(Polymorphism): 允许动态分配对象,但可以预测对象的行为
  • Inheritance - the ability to inherit and extend existing functionality.
  • Encapsulation - the ability to allow the user to only see specific parts, and to interact with it in specific ways.
  • Polymorphism - the ability for an object to be assigned dynamically, but with some predictability as to what can be done with the object.

存在两种类型的对象:

  • 引用类型(Reference types
  • 值类型(Value types

引用类型和值类型

引用类型就像指向值的指针,而值类型就是值本身,值类型在存储少量信息时很好用。

System.Object

为了遵循 OOP 的第一条规则 - 继承,所有对象都将继承自 System.Object 这个对象,这个对象定义了一些供所有对象使用的方法,包括:

  • GetHashCode()
  • GetType()
  • ToString()

对象基础知识

所有对象默认都是引用类型,为了支持值类型,对象必须继承自 System.ValueType,而不是 System.Object。

构造器

当对象被创建时,它们被构造器初始化。构造器是隐式创建的,除非开发者定义了不同于默认的构造器。存在 3 类构造器:

  • 复制构造器(Copy Constructor
  • 静态构造器(Static Constructor
  • 默认构造器(Default Constructor
  • 重载构造器(Overloaded Constructor

在 C# 中,构造器是特殊的方法。构造方法的重要特征有:

  1. 构造方法的名称与类名相同
  2. 构造方法通常被声明为 public
  3. 构造方法被声明为 public 的原因是为了能够从类的外部创建对象。构造方法也可以被声明为 private,不过这样的构造函数不能用于创建对象
  4. 构造方法没有返回类型(甚至没有 void)
  5. C# 为每个类提供了默认的构造方法,默认的构造方法将成员初始化为 0,若编写了自定义的构造方法,则不会使用默认的构造方法
  6. 构造方法用于给成员变量赋值
  7. 当对象被创建时,new 关键字调用构造方法
  8. 可以定义不止一个构造方法,这被称为构造器重载。所有构造方法具有相同的名称,但具有数量或类型不同的参数
  9. 若声明了构造器,则默认的构造器不会生成
  1. A constructor method has the same name as the class itself.
  2. A constructor method is usually declared as public.
  3. Constructor method is declared as public because it is used to create objects from outside the class in which it is declared. We can also declare a constructor method as private, but then such a constructor cannot be used to create objects.
  4. Constructor methods do not have a return type (not even void).
  5. C# provides a default constructor to every class. This default constructor initializes the data members to zero. But if we write our own constructor method, then the default constructor is not used.
  6. A constructor method is used to assign initial values to the member variables.
  7. The constructor is called by the new keyword when an object is created.
  8. We can define more than one constructor in a class. This is known as constructor overloading. All the constructor methods have the same name, but their signatures are different, i.e., number and type of parameters are different.
  9. If a constructor is declared, no default constructor is generated.

复制构造器(Copy Constructor

using System;

namespace CopyConstructor
{
    class Rectangle
    {
        public int length;
        public int breadth;

        public Rectangle(int x, int y)         // constructor fn
        {
            length = x;
            breadth = y;
        }

        public Rectangle(Rectangle r)
        {
            length = r.length;
            breadth = r.breadth;
        }

        public void display()
        {
            Console.WriteLine("Length = " + length);
            Console.WriteLine("Breadth = " + breadth);
        }
    }   // end of class Rectangle

    class Program
    {
        public static void Main()
        {
            Rectangle r1 = new Rectangle(5, 10);
            Console.WriteLine("Values of first object");
            r1.display();

            Rectangle r2 = new Rectangle(r1);
            Console.WriteLine("Values of second object");
            r2.display();

            Console.ReadLine();
        }
    }
}

静态构造器(Static Constructor

静态构造器在类被加载时就调用一次,且仅在此调用一次。

using System;
using System.Collections.Generic;
using System.Text;

namespace StaticConstructors
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            int j = 0;
            Console.WriteLine("Static Number = " + MyClass.Number);
        }
    }

    class MyClass
    {
        private static int _number;
        public static int Number { get { return _number; } }
        static MyClass()
        {
            Random r = new Random();
            _number = r.Next();
        }
    }
}

默认构造器(Default Constructor

默认构造器没有参数,并且是隐式定义的。

// Created by the developer
class MyClass
{
}

// Created by the compiler
class MyClass : System.Object
{
     public MyClass() : base()
     {
     }
}

重载构造器(Overloaded Constructor

 class MyClass
    {
        private int _number;
        public int Number { get { return _number; } }
        
        public MyClass()
        {
            Random randomNumber = new Random();
            _number = randomNumber.Next();
        }
  
        public MyClass(int seed)
        {
            Random randomNumber = new Random(seed);
            _number = randomNumber.Next();
        }
   }
调用其他构造器

如果其他构造器能更好地实现功能,可以在构造器中调用其他带有特定参数的重载构造器(或默认构造器)。

class MyClass
    {
        private int _number;
        public int Number { get { return _number; } }
        
        public MyClass() : 
             this ( DateTime.Now.Milliseconds ) // Call the other constructor passing in a value.
        {
            
        }
  
        public MyClass(int seed)
        {
            Random r = new Random(seed);
            _number = r.Next();
        }
   }

不仅可以调用当前实例的构造器,还可以调用基类的构造器。

class MyException : Exception
    {
        private int _number;
        public int Number { get { return _number; } }
        
        public MyException ( int errorNumber, string message, Exception innerException)
                 : base( message, innerException )
        {
             _number = errorNumber;
        }
   }

终结器

终结器名称与类名相同,但名称前面有波浪号(~),且没有访问修饰符,仅当垃圾回收器起作用时,终结器才会被调用。

class MyException : Exception
    {
        private int _number;
        public int Number { get { return _number; } }
        
        public MyException ( int errorNumber, string message, Exception innerException)
                : base( message, innerException )
        {
             _number = errorNumber;
        }

        ~MyException()
        {
        }
   }