C#构造函数

/ / C#构造函数

在C#中,构造函数是在创建对象时自动调用的特殊方法。一般用于初始化新对象的数据成员。C#中的构造函数与class或struct同名。

在C#中可以有两种类型的构造函数。

  • Default constructor
  • Parameterized constructor

C#默认构造函数

没有参数的构造函数称为默认构造函数。它在创建对象时调用。

using System;
   public class Employee
    {
        public Employee()
        {
            Console.WriteLine("Default Constructor Invoked");
        }
        public static void Main(string[] args)
        {
            Employee e1 = new Employee();
            Employee e2 = new Employee();
        }
    }

输出:

无涯教程网

Default Constructor Invoked 
Default Constructor Invoked

让无涯教程看看默认构造函数的另一个示例,其中在另一个类中使用main()方法。

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-constructor.html

来源:LearnFk无涯教程网

using System;
   public class Employee
    {
        public Employee()
        {
            Console.WriteLine("Default Constructor Invoked");
        }
    }
   class TestEmployee{
       public static void Main(string[] args)
        {
            Employee e1 = new Employee();
            Employee e2 = new Employee();
        }
    }

输出:

无涯教程网

Default Constructor Invoked 
Default Constructor Invoked

C#参数化构造函数

具有参数的构造函数称为参数化构造函数。它用于为不同的对象提供不同的值。

using System;
   public class Employee
    {
        public int id; 
        public String name;
        public float salary;
        public Employee(int i, String n,float s)
        {
            id = i;
            name = n;
            salary = s;
        }
        public void display()
        {
            Console.WriteLine(id + " " + name+" "+salary);
        }
   }
   class TestEmployee{
       public static void Main(string[] args)
        {
            Employee e1 = new Employee(101, "Sonoo", 890000f);
            Employee e2 = new Employee(102, "Mahesh", 490000f);
            e1.display();
            e2.display();

        }
    }

输出:

无涯教程网

101 Sonoo 890000
102 Mahesh 490000

祝学习愉快! (发现内容有误?请选中要编辑的内容 -> 右键 -> 修改 -> 提交!帮助我们改进教程质量)

精选教程推荐

👇 以下精选教程可能对您有帮助,拓展您的技术视野

性能优化高手课 -〔尉刚强〕

Spring编程常见错误50例 -〔傅健〕

大厂晋升指南 -〔李运华〕

Spark核心原理与实战 -〔王磊〕

Serverless入门课 -〔蒲松洋(秦粤)〕

SRE实战手册 -〔赵成〕

网络编程实战 -〔盛延敏〕

软件工程之美 -〔宝玉〕

重学前端 -〔程劭非(winter)〕

📝 好记忆不如烂笔头,留下您的学习笔记吧!

暂无学习笔记,成为第一个分享的人吧!

您的笔记将帮助成千上万的学习者