c#/VB.net属性-设置程序的私有访问修饰符的好处/优势是什么
下面是具有属性的类c#/VB.net属性-设置程序的私有访问修饰符的好处/优势是什么,c#,asp.net,vb.net,c#-4.0,properties,C#,Asp.net,Vb.net,C# 4.0,Properties,下面是具有属性的类 public class abc { public int MyProperty { get; private set; } } 混淆-在setter中键入private access修饰符有什么好处?简单地说,它是允许类本身设置的属性,但外部对象只能读取。也许MyProperty作为方法的副作用而更改,也许它只设置一次(在构造函数中)。主要的一点是,MyProperty的更改源必须来自abc(或一个嵌套的abc)类内部,而不是来自持有对它的
public class abc
{
public int MyProperty { get; private set; }
}
混淆-在setter中键入private access修饰符有什么好处?简单地说,它是允许类本身设置的属性,但外部对象只能读取。也许
MyProperty
作为方法的副作用而更改,也许它只设置一次(在构造函数中)。主要的一点是,MyProperty
的更改源必须来自abc
(或一个嵌套的abc
)类内部,而不是来自持有对它的引用的外部
至于为什么您可能会使用它,可能无法信任外部代码来设置此值。该类不是严格不可变的,它可以更改,但该类(或嵌套类)中存在唯一受信任执行该操作的代码。外部世界可以简单地读取。私有setter只允许在类内部设置属性,而getter仍然公开属性值。私有修饰符允许在公共、受保护或内部访问的上下文中只读属性,同时赋予类型本身设置属性的能力(即在私有访问的上下文中)。使用私有集有几个原因 1) 如果您根本不使用备份字段,并且想要只读自动属性:
public class abc
{
public int MyProperty { get; private set; }
}
2) 如果您想在修改类内的变量时做额外的工作,并想在单个位置捕获该变量,请执行以下操作:
private string _name = string.Empty;
public string Name
{
get { return _name; }
private set
{
TextInfo txtInfo = Thread.CurrentThread.CurrentCulture.TextInfo;
_name = txtInfo.ToTitleCase(value);
}
}
不过,总的来说,这是个人偏好的问题。据我所知,使用一个属性而不是另一个属性是没有性能原因的。这样做是为了使属性成为只读的,这样外部世界就不允许更改属性的值,并且只有实现属性的类才能更改作为属性所有者的属性值。 例如,类如何跟踪其实例计数,实例计数只能从类内部增加/减少,不允许外部世界更改实例计数属性,例如:
public class Customer
{
public Customer()
{
InstanceCount++;
}
//Helps retrieving the total number of Customers
public int InstanceCount { get; private set; } //Count should not be increased by the clients of this class rather should be increased in the constructor only
}
在某些情况下,另一个好处是,在为属性提供私有集后,当您希望对接收到的值进行一些计算或验证时,可以提供一个用于从外部世界更改属性值的set方法(这不是在set属性访问器内执行的最佳做法),然后按如下方式更改属性的值:
public class Customer
{
public string City { get; private set; }
public bool SetCity(string customerCity)
{
//validate that the customerCity is a valid USA city or else throw some business rule exception, and then call below code
City = customerCity
}
}