在C#中类的构造器,与类中的方法是如何区分的?
class student
{
public student{}//类的构造方法
}static void Main()
{
student s =new student();//类的实例化 student()也是构造方法}请问:public student{}//类的构造方法 跟主函数的student()构造方法;有什么区别?越详细越好。
类的构造方法是不是?唯一作用就是初始化字段/属性的值?
class student
{
public student{}//类的构造方法
}static void Main()
{
student s =new student();//类的实例化 student()也是构造方法}请问:public student{}//类的构造方法 跟主函数的student()构造方法;有什么区别?越详细越好。
类的构造方法是不是?唯一作用就是初始化字段/属性的值?
{
方法体
}如果没有写构造函数,CLR会调用默认的无参共有构造函数。构造函数可以重载,根据初始化调用匹配最接近的一个。构造函数不能有返回值类型修饰,也不能有返回值,正是这一点,使得它不可能和普通方法混淆。
{
static void Main(string[] args)
{
student xx;
xx = new student();//
//xx.name = "张三";
Console.WriteLine(xx.name);
Console.ReadKey();
}
}
class student
{
public string name;
int age;
public student()//类的构造方法
{
this.name = "李四";
}
}
这个public student()//类的构造方法跟主函数 xx = new student();//不同点在哪儿?
最重要的是构造类型对象用的。(C#中一切都是对象)看下面两句:
(一)、int a=6;
(二)、int a=new int();
a=6;第二种是全写,第一种是简写,一个类型的对象在创建时,都需要通过构造方法来构造。
没有区别,如上面3楼所说,一个是调用,一个是定义构造器。在调用后,xx对象的name成员值已被初始化为"李四"