C#类的创建与初始化实例解析
本文以一个实例简单实现了类的创建与初始化,实现代码如下所示:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespaceC_program_test
{
classPerson
{
publicstringName;//因为Name没有赋值,而它是string类型的,所以它的默认值就是Null
publicintAge;//因为Age和Gender也没有赋值,而它两是int类型的,所以他们两个的默认值为0
publicintGender;
publicvoidsayHello()
{
Console.WriteLine("大家好");
Console.ReadKey();
}
}
classProgram
{
staticvoidMain(string[]args)
{
//inti=1;//值类型初始化就是直接赋值。而引用类型初始化就需要new
Personp1=newPerson();//newPerson()就是创建一个Person类对象。Personp1=newPerson()就是指先创建一个Person类型的对象然后用变量p1指向它
p1.sayHello();
}
}
}