📅  最后修改于: 2023-12-03 14:55:10.283000             🧑  作者: Mango
When programming in C#, it is common practice to use getters and setters to provide access to private fields. In this article, we'll cover what getters and setters are, how to write them, and how to use them in your code.
Getters and setters are methods that allow you to access and modify private fields in a class. A getter is typically used to retrieve the value of a field, while a setter is used to set the value of a field.
When you define a property in a C# class, you can use a getter and a setter to control access to that property. This is known as encapsulation, as it keeps the inner workings of the class hidden and allows you to control how external code interacts with it.
To write a getter or setter in C#, you can use the get
and set
keywords. Here's an example getter/setter for a private field _name
:
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
In this example, the get
keyword is used to return the value of the _name
field, while the set
keyword is used to set the value of the _name
field.
Once you've defined a getter and setter for a property, you can use it just like any other property. Here's an example:
MyClass myClass = new MyClass();
myClass.Name = "John Doe";
Console.WriteLine(myClass.Name);
In this example, we're creating a new instance of the MyClass
class and setting its Name
property to "John Doe"
. We can then use the Name
property to retrieve the value of the _name
field.
Getters and setters in C# are a powerful tool for controlling access to private fields in your classes. By using getters and setters to encapsulate your code, you can control how external code interacts with your class and ensure that it behaves as expected.