How to define a class in C#?

In C#, the class keyword can be used to define a class. Here is a simple example showing how to define a class named Person:

class Person
{
    // 类的字段(属性)
    public string Name { get; set; }
    public int Age { get; set; }
    
    // 类的方法
    public void SayHello()
    {
        Console.WriteLine("Hello, my name is " + Name + " and I am " + Age + " years old.");
    }
}

In the example provided, the Person class has two properties (fields): Name and Age, as well as a method called SayHello(). Properties are used to store the class’s state information, while methods define the class’s behavior. The public keyword indicates that these members are accessible from outside the class.

By instantiating a Person object, you can use the class.

Person person = new Person();
person.Name = "John";
person.Age = 25;
person.SayHello();  // 输出:Hello, my name is John and I am 25 years old.

In this way, you can create an instance of the Person class and call its methods to perform specific operations.

bannerAds