当前位置: 代码迷 >> 综合 >> c#学习-构造函数
  详细解决方案

c#学习-构造函数

热度:21   发布时间:2024-02-09 09:59:38.0

特点:

  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
{#region/*class Dog {public string name;public  int age;public char gender;public static string kind;public void Eat() {Console.WriteLine(name+"    Eat");}public void Drink(){Console.WriteLine(name+"    Drink");}static public void Kind(){Console.WriteLine(Dog.kind+"    拆迁队队长");//包子的皮和馅要对应}}*/#endregionclass   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){#region/*Dog hashiqi = new Dog();hashiqi.name = "Aqi";hashiqi.Eat();hashiqi.Eat();hashiqi.gender = 'M';Dog.kind = "哈士奇";Dog.Kind();*/#endregion/*Person xiaoming = new Person();//无参被调用Person daming = new Person("daming",15);//传值Person taotao = new Person("taotao", 26,178,200);//传值+调用*/Person.show();//静态构造函数被执行,静态方法被执行}}
}

 

  相关解决方案