zl程序教程

您现在的位置是:首页 >  后端

当前栏目

c#学习-构造方法

c#学习 构造方法
2023-09-27 14:27:29 时间

特点:

  1. 没有返回值,连void也不能写。
  2. 构造方法名必须是雷鸣
  3. 构造方法不能显示调用,在实例化对象时被自动调用

作用:

用来实例化一个对象

注意:

  1. 如果一个类中没有写构造方法,那么系统会给一个默认的无参public权限的构造方法
  2.  如果类中已经写了构造方法了,那么这个默认的构造方法不再被提供。

参考代码:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _2020cexample
{
    class   Person {
     public   string name;
     public   int age;
     public float height;
     public float weight;
    static Person() {
            Console.WriteLine("静态构造函数被调用");//首先输出
        }
    
    public Person() {
        Console.WriteLine("无参构造函数被调用");
    
    }
    public Person(string name,int age)
        {
            this.name = name;
            this.age = age;
            Console.WriteLine("构造函数可以用来传值");
        }
    public Person(string name, int age, float heiht, float weight):this (name,age)
        {

            this.height = height;
            this.weight = weight;
            Console.WriteLine("构造函数如果不想重复,可以把之前的构造函数调用一下");
        }

        public static void show() {
            Console.WriteLine("静态方法被执行");
        }
    }
    

    class Program
    {
        static void Main(string[] args)
        {
          
            Person xiaoming = new Person();//无参被调用
            Person daming = new Person("daming",15);//传值
            Person taotao = new Person("taotao", 26,178,200);//传值+调用
            Person.show();//静态构造函数被执行,静态方法被执行
       
        }
    }
}