How is “get” used in C#?

In C#, the “get” keyword is used to define a property’s getter method, which is used to retrieve the value of the property. Typically, the “get” method will return the value of the property to the caller. Here is an example using the “get” method:

public class Person
{
    private string _name;

    public string Name
    {
        get { return _name; }
    }
}

Person person = new Person();
person.Name = "Alice"; // 编译错误,因为Name属性只有getter方法,不能被赋值
string name = person.Name; // 正确,调用getter方法获取属性值
Console.WriteLine(name); // 输出 "Alice"
bannerAds