C#类的定义(包括构造函数的例⼦)类是对现实世界抽象所得到的结果
类就是 class + 类名 + 类体
下⾯是关于类的简单应⽤的⼀个⼩例⼦:
class Program
{
static void Main(string[] args)
{
Student stu =new Student(1,"tt");
//这个空的圆括号就是实例默认构造器
// 作⽤是把类⾥的字段清成默认值
stu.Report();
}
}
class Student
//这是⼀个抽象的载体,他⾥⾯的成员也是抽象的⼀个内容
{
public Student(int id,string name)
{
this.ID = id;
this.Name = name;
}
//这⾥⽤ctor快捷键就能⾃⼰写构造器了
~Student()
{
Console.WriteLine("拜拜了您,收回您的资源了");
//这是⼀个吸构器,收回资源的
}
public string Name {get;set;}//这⾥是创建的属性字段
public int ID {get;set;}
public void Report()
{
Console.WriteLine($"I'm # {ID}student,My name is {Name}");
//这⾥加了¥,才能让花括号⾥的数值直接带⼊进去
}
}
上述代码还⽤到了构造器,是刚刚学习时,有点疑惑的地⽅
静态成员是指对⼀个宏观的类有意义的时候使⽤例如下⾯,是代表学⽣这个整体的⼀个总数。public static int Amount {get;set;}//构造了静态属性
static Student()
{
Amount =100;
writeline函数}
当在主程序就需要⽤类来调⽤了:
static void Main(string[] args)
{
Console.WriteLine(Student.Amount);
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论