C# 中不同类型的构造函数

ops/2024/10/18 5:57:36/

介绍

在本文中,我们将学习 C# 中的构造函数和构造函数类型。C# 中有五种不同类型的构造函数。构造函数用于创建类的对象。以下是 C# 中的构造函数列表。

  • 默认构造函数
  • 参数化构造函数
  • 复制构造函数
  • 静态构造函数
  • 私有构造函数

什么是构造函数?

构造函数是一种用于初始化对象的特殊方法。构造函数在创建对象时调用。构造函数名称必须与其类名相同。构造函数不得有显式返回类型。

构造函数和方法的区别

默认构造函数

没有任何参数的构造函数称为默认构造函数。如果我们不创建构造函数,则类将在创建对象时自动调用默认构造函数。

例子

using System;
namespace DefaultConstructor_Demo
{public class Customer{public string firstName;public string lastName;public Customer(){}}class Program{static void Main(string[] args){Customer customer = new Customer();customer.firstName = "Farhan";customer.lastName = "Ahmed";Console.WriteLine("Full Name: " + customer.firstName + " " + customer.lastName);Console.ReadLine();}}
}

参数构造函数

至少具有一个参数的构造函数称为参数化构造函数。

例子

using System;
namespace ParameterConstructor_Demo
{class ParameterConstructor{public int FirstNumber;public int SecondNumber;public ParameterConstructor(int firstNumber, int secondNumber){FirstNumber = firstNumber;SecondNumber = secondNumber;}}class Program{static void Main(string[] args){ParameterConstructor p = new ParameterConstructor(10, 20);int Result = p.FirstNumber + p.SecondNumber;Console.WriteLine("Total:" + Result);Console.ReadLine();}}
}

复制构造函数

通过从另一个对象复制变量来创建对象的构造函数称为复制构造函数。

例子

using System;
namespace CopyConstructor_Demo
{public class Employee{public string firstName;public string lastName;public string position;public int salary;public Employee(){}// Copy constructor.public Employee(Employee employee){firstName = employee.firstName;lastName = employee.lastName;position = employee.position;salary = employee.salary;}}class Program{static void Main(string[] args){Employee emp = new Employee();Employee emp1 = new Employee(emp);Console.WriteLine("Enter your first name:");emp1.firstName = Convert.ToString(Console.ReadLine());Console.WriteLine("Enter your last name:");emp1.lastName = Convert.ToString(Console.ReadLine());Console.WriteLine("Enter your position:");emp1.position = Convert.ToString(Console.ReadLine());Console.WriteLine("Enter your salary:");emp1.salary = Convert.ToInt32(Console.ReadLine());Console.WriteLine("First Name:" + emp1.firstName);Console.WriteLine("Last Name:" + emp1.lastName);Console.WriteLine("Position:" + emp1.position);Console.WriteLine("Salary:" + emp1.salary);}}
}

静态构造函数

静态构造函数用于初始化任何静态数据或执行只需执行一次的特定操作。它在创建第一个实例或引用任何静态成员之前自动调用。

静态构造函数的特点

  • 静态构造函数不接受任何访问修饰符。
  • 静态构造函数没有参数。
  • 在创建第一个实例或引用任何静态成员之前,会自动调用静态构造函数来初始化类。
  • 静态构造函数不能被直接调用。
  • 用户无法控制程序中静态构造函数的执行时间。
  • 静态构造函数的典型用途是当类使用日志文件时,构造函数用于将条目写入该文件。
  • 一个类只能有一个静态构造函数。
  • 它只能访问类的静态成员。

例子

using System;
namespace StaticConstructor_Demo
{public class Customer{public string firstName;public string lastName;public static string discount;public Customer(string FirstName, string LastName){firstName = FirstName;lastName = LastName;}static Customer(){discount = 10 + "%";}public void CustomerDetails(){Console.WriteLine("Full Name:{0}", firstName + " " + lastName);Console.WriteLine("Discount:{0}", discount + "\n");}}class Program{static void Main(string[] args){Customer c1 = new Customer("Farhan", "Ahmed");Customer c2 = new Customer("Abdul", "Jabbar");c1.CustomerDetails();c2.CustomerDetails();Console.ReadLine();}}
}

私有构造函数

私有构造函数是一种特殊的实例构造函数。它通常用于仅包含静态成员的类中。如果一个类有一个或多个私有构造函数,而没有公共构造函数,则其他类(嵌套类除外)无法创建此类的实例。私有构造函数的用途是为单例类提供服务。单例类是将创建的对象数量限制为一个的类。使用私有构造函数,我们可以确保一次只能创建一个对象

  • 私有构造函数的一个用途是当我们只有一个静态成员时。
  • 它提供了单例类模式的实现。
  • 一旦我们提供了一个构造函数(private/public/any),编译器就不会将无参数的公共构造函数添加到任何类中。

例子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrivateConstructor_Demo
{public class Candidate{private Candidate(){}public static int CandidateVisitedForInterview;public static int CountCandidate(){return ++CandidateVisitedForInterview;}}class Program{static void Main(string[] args){// The following comment line will throw an error because constructor is inaccessible//Candidate candidate = new Candidate();Candidate.CandidateVisitedForInterview = 20;Candidate.CountCandidate();Console.WriteLine("Interviewed candidates: {0}", Candidate.CandidateVisitedForInterview);Console.ReadLine();}}
}

http://www.ppmy.cn/ops/52309.html

相关文章

(转)请介绍一下Redis的数据淘汰策略

1. **NoEviction(不淘汰)**:当内存不足时,直接返回错误,不淘汰任何数据。该策略适用于禁止数据淘汰的场景,但需要保证内存足够。 2. **AllKeysLFU(最少使用次数淘汰)**:…

如何关闭软件开机自启,提升电脑开机速度?

如何关闭软件开机自启,提升电脑开机速度?大家知道,很多软件在安装时默认都会设置为开机自动启动。但是,有很多软件在我们开机之后并不是马上需要用到的,开机启动的软件过多会导致电脑开机变慢。那么,如何关…

【计算机网络篇】数据链路层(13)共享式以太网与交换式以太网的对比

文章目录 🍔共享式以太网与交换式以太网的对比🔎主机发送单播帧的情况🔎主机发送广播帧的情况🔎多对主机同时通信 🛸使用集线器和交换机扩展共享式以太网的区别 🍔共享式以太网与交换式以太网的对比 下图是…

react实现窗口悬浮框,可拖拽、折叠、滚动

1、效果如下 2、如下两个文件不需要修改 drag.js import React from "react"; import PropTypes from "prop-types";export default class DragM extends React.Component {static propTypes {children: PropTypes.element.isRequired};static defaultP…

华为某员工爆料:偷偷跑出去面试,被面试官鄙视了。第一句话就问:华为淘汰的吧,35岁了,这个年龄在华为能混得下去吗?身体没啥毛病吧

“你都35岁了,难不成是被华为淘汰的?在华为混不下去了吧?身体没啥毛病吧,我们这体检可是很严的。” 近日,一位华为员工在朋友圈爆料,自己在面试时遭到了面试官的无理取闹和人身攻击,原因仅仅是因…

css如何动态累计数字?

导读:css如何动态累计数字?用于章节目录的序列数生成,用css的计数器实现起来比 js方式更简单! 伪元素 ::after ::before伪元素设置content 可以在元素的首部和尾部添加内容,我们要在元素的首部添加序列号&#xff0c…

6.二叉树.遍历

6.二叉树.遍历 深度优先遍历二叉树的递归遍历二叉树的迭代遍历 广度优先遍历 深度优先遍历 二叉树的递归遍历 递归算法的三个要素: 确定递归函数的参数和返回值: 确定哪些参数是递归的过程中需要处理的,那么就在递归函数里加上这个参数&am…

Android使用DevRing框架搭建数据库实体类以及使用

一、引用DevRing依赖 //导入DevRing依赖implementation com.ljy.ring:devring:1.1.8创建数据库表的依赖implementation org.greenrobot:greendao:3.2.2 // add libraryimplementation org.greenrobot:greendao-generator:3.0.0 二、修改工程目录下的.idea->gradle.xml文件&…