类的构造函数

构造函数是在实例化对象时自动调用的特殊函数,必须与所属的类名同名,不能有返回类型。用于初始化字段的值。

目前我见到的构造函数  按照有无参数分为 有参数的构造函数和无参数的构造函数,但是还有一种是  静态构造函数,就不知道如何划分了。

所有的类都是继承object类的,所以如果没有写构造函数,默认的构造函数就是object类的无参数构造函数。如果指定了无参数构造函数,那无参数构造函数就是该类的默认构造函数。

尝试代码如下:

public class A
    {
        public A()
        {
            Console.WriteLine("A()");
        }

        public A(int a,int b)
        {
            Console.WriteLine("A(int a,int b)");
        }
    }

    public class B:A
    {
        public static string s;
        public B()
        {
            Console.WriteLine("B()");
        }

        public B(int a, int b)
        {
            Console.WriteLine("B(int a,int b)");
        }
    }

    public class C:B 
    {
        public C()
        {
            Console.WriteLine("C()");
        }

        public C(int a, int b):base(a,b)
        {
            Console.WriteLine("C(int a,int b)");
        }
    }
class Program
    {
        static void Main(string[] args)
        {
            C c = new C(7, 8);
            Console.ReadKey();
        }
    }

执行子类的构造函数先调用父类的构造函数。

1、上述执行函数顺序:A() =》B(int a,int b)=》C(int a, int b)   C类的有参数构造函数基于父类B的有参数构造函数,base(a,b)。

2、public C(int a, int b):base(a,b) 换成public C(int a, int b)   执行函数顺序:A() =》B()=》C(int a, int b)  C类的有参数构造函数 不是基于父类B的 有参数构造函数,因此父类构造函数调用的是无参数的。

3、若B类只有 有参数构造函数,则C类 也只能有  有参数构造函数 并且是基于B类的,具体见下:

public class A
    {
        public A()
        {
            Console.WriteLine("A()");
        }

        public A(int a,int b)
        {
            Console.WriteLine("A(int a,int b)");
        }
    }

    public class B:A
    {
        public static string s;
        //public B()
        //{
        //    Console.WriteLine("B()");
        //}

        public B(int a, int b)
        {
            Console.WriteLine("B(int a,int b)");
        }
    }

    public class C:B 
    {
        //public C()
        //{
        //    Console.WriteLine("C()");
        //}

        public C(int a, int b)
            : base(a, b)
        {
            Console.WriteLine("C(int a,int b)");
        }
    }
View Code

执行函数顺序:A() =》B(int a,int b)=》C(int a, int b)

4.静态构造函数 是第一次执行这个类是执行的函数。

本人目前对类的构造函数的认识只有这么多,以后认识更多再重新整理。

原文地址:https://www.cnblogs.com/see-you/p/3958420.html