How to create and use classes in C#?
To create a class in C#, you can follow these steps:
- Define a class using the keyword “class”, and then write the class members within the curly braces.
public class MyClass
{
// 类的成员
}
- Define fields, properties, methods, and other members within a class.
public class MyClass
{
public int MyField;
public void MyMethod()
{
// 方法实现
}
}
- This class can be instantiated in other classes and its members can be called.
MyClass myObject = new MyClass();
myObject.MyField = 10;
myObject.MyMethod();
- You can initialize an instance of a class by using a constructor.
public class MyClass
{
public int MyField;
public MyClass(int value)
{
MyField = value;
}
}
- Using inheritance to create subclasses is possible.
public class MySubClass : MyClass
{
public void MySubMethod()
{
// 子类方法实现
}
}
- Access modifiers such as public, private, and protected can be used to control the accessibility of a class’s members.
These are the basic steps to create and use classes in C#, with which you can define your own class and use its members.