Class (class) is the basic C# type. A class is a data structure that combines fields and methods in one unit.
1. Defined class
Defined class generally includes: modifier, class , class name.
Without modifier, it defaults to private class
//定义 学生类
class Student
{
//数据-变量
public string name;
public int age;
//行为-方法
public void SayName()
{
Console.WriteLine("我是:" + name);
}
}
//矩形类
class Rect
{
//数据
public float l;//长
public float w;//宽
//行为
public float GetArea() //求面积
{
return l * w;
}
public float GetPerimeter() //求周长
{
return (l + w) * 2;
}
}
Class generally contains class members, class methods, etc.
2. Create an object
Student s1 = new Student();//创建一个学生对象
Rect rect1 = new Rect();//创建一个矩形对象
3. Access modifier
Access modifier | restriction of visit |
---|---|
public | Public, no access restrictions |
private | Private, can only be accessed within this class, subclasses and instances cannot be accessed |
protected | Protected, limited to this class and subclasses, the instance cannot be accessed |
internal | Inside the program, only accessible within this project |
protected internal | The internal protection of the program is limited to this project or sub-category access |
4. Constructor
Constructor: Without writing the return value, the method name is the same as the class name.
When creating an object, the constructor will be called automatically. If there is a parent class, the parent class constructor will be called first. The constructor is mainly used to initialize member variables.
If we do not write a constructor, the system will provide a default constructor. If the constructor is written, it will no longer be provided.
class MyClass
{
public int x;
public int y;
public int z;
public MyClass()
{
}
public MyClass(int x,int y) //我们写的有参数的构造函数
{
this.x = x;
this.y = y;
}
public MyClass(int x, int y, int z) :this(x,y)
{
this.z = z;
}
}
Among them : this() is to call the sibling constructor, that is, to call the above
public MyClass(int x,int y)
{
this.x = x;
this.y = y;
}
Avoid duplication of code.