我是一个VBA开发者和新的C# 下面是我的Employee类:如何强制用户使用方法更改类字段,而不是直接更改它?
class Employee
{
public string name;
public Employee()
{
age = 0;
}
public void setName(string newName)
{
name = newName;
}
}
当我创造我Employeeclass的对象,我既可以使用所提供的设置名称值的方法
Employee E1 = new Employee();
E1.setName("Name 1");
或者我可以直接设置名称。
Employee E1 = new Employee();
E1.name = "Name 1"
整点是如何阻止用户设置我的领域直接/的价值不叫我的方法,如果你能告诉我,我怎么能有效地设置我的类字段的值。
通过使字段私人。 [访问修饰符(C#编程指南)](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers)/ [private(C#Reference)] (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private) – Nkosi
使您的字段/属性为“private”而非public,以便类之外的其他函数不能访问它们 –