c#构造函数它的返回值是什么?

时间:2022-02-22 19:26:10
代码如下:
Employee []employees=new Employee[3];
employees[0]=new Employee("张三","18","001");
employees[0]=new Employee("李四","18","002");
employees[0]=new Employee("王五","18","003");

上面这段代码在VS环境下是可行的。但构造函数返回的是什么值呢?难道是个对象吗?

6 个解决方案

#1


构造函数没有返回值,

new调用构造函数,返回新生成的类实例的引用,new Employee返回指向Employee对象的引用,

#2


Employee []employees=new Employee[3];
employees[0]=new Employee("张三","18","001");
employees[0]=new Employee("李四","18","002");
employees[0]=new Employee("王五","18","003");

=>

Employee []employees=new Employee[3];
employees[0]=new Employee("张三","18","001");
employees[ 1]=new Employee("李四","18","002");
employees[ 2]=new Employee("王五","18","003");

#3


构造函数的任务是初始化类的实例,它本身不创建类的实例,所以它不会返回类实例的引用,它什么都不返回,也不返回void,构造函数就是没有返回值,

类的实例是new运算符创建的,new运算符创建了类的实例,然后调用构造函数对新生成的类实例进行初始化,然后返回类的实例的引用,

#4


Employee []employees=new Employee[3];
返回的是一个有3个元素的数组,每个元素都是null。
Employee []employees=new Employee[3];
等效
Employee[] employees = new Employee[] { null. null, null };

#5


new是一个运算符,new Employee("张三","18","001")是一个表达式,而不是简单的调用构造函数,而是创建实例后调用构造函数,

#6


构造函数作用是初始化。。。不能返回任何值

#1


构造函数没有返回值,

new调用构造函数,返回新生成的类实例的引用,new Employee返回指向Employee对象的引用,

#2


Employee []employees=new Employee[3];
employees[0]=new Employee("张三","18","001");
employees[0]=new Employee("李四","18","002");
employees[0]=new Employee("王五","18","003");

=>

Employee []employees=new Employee[3];
employees[0]=new Employee("张三","18","001");
employees[ 1]=new Employee("李四","18","002");
employees[ 2]=new Employee("王五","18","003");

#3


构造函数的任务是初始化类的实例,它本身不创建类的实例,所以它不会返回类实例的引用,它什么都不返回,也不返回void,构造函数就是没有返回值,

类的实例是new运算符创建的,new运算符创建了类的实例,然后调用构造函数对新生成的类实例进行初始化,然后返回类的实例的引用,

#4


Employee []employees=new Employee[3];
返回的是一个有3个元素的数组,每个元素都是null。
Employee []employees=new Employee[3];
等效
Employee[] employees = new Employee[] { null. null, null };

#5


new是一个运算符,new Employee("张三","18","001")是一个表达式,而不是简单的调用构造函数,而是创建实例后调用构造函数,

#6


构造函数作用是初始化。。。不能返回任何值