构造函数的需求是什么以及为什么使用构造函数 [英] What is the need of constructors and why constructors are used

查看:91
本文介绍了构造函数的需求是什么以及为什么使用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构造函数的需求是什么以及为什么使用构造函数



我尝试过:



构造函数需要什么以及为什么使用构造函数

what is the need of constructors and why constructors are used

What I have tried:

what is the need of constructors and why constructors are used

推荐答案

构造函数在那里,以便在创建类的实例时当你试图使用它时,可以确保它具有所有必需的信息。

假设你有一个Person类 - 你不能在不知道有关它们的大量信息的情况下构建一个人:他们的例如,姓名,出生日期和地址。

提供构造函数可以确保在创建Person时提供信息以便您可以执行此操作:

Constructors are there so that when you create an instance of a class you can ensure that it has all the required information available when you try to use it.
Assume you have a Person class - you can't construct a Person without knowing a fair amount of information about them: their name, date of birth, and address for example.
Providing a constructor allows you to be sure that when the Person is created that information is supplied so that you can do this:
Person mike = new Person("Mike Smith", new DateTime(1999, 1, 17), "3, Larch Lane, LarchTon");
Console.WriteLine(mike.Age());

因为你的Person构造函数坚持我在创建实例时提供出生日期,所以我可以调用Age方法并知道它赢了没问题。

默认构造函数也是如此:它们可以让你确保类需要做的所有工作都是在使用实例之前创建并准备就绪。

Because your Person constructor insisted that I provide the date of birth when I create the instance, I can call the Age method and know it won't have a problem.
The same is true for default constructors: they let you ensure that everything the class needs to do it's job is created and ready before the instance is used.


构造函数是一种名称与类名称相同的方法,它有两种类型1.默认构造函数2.带参数的构造函数

默认构造函数由它自己调用。



它用于在执行开始之前初始化要初始化的变量。
Constructor is one type of method named same as class name, it's of two type 1. Default Constructor 2. Constructor with Parameters
Default constructor calls by it self.

it's used to initialise variables to which you want to initialise before execution starts.


这篇关于构造函数的需求是什么以及为什么使用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆