变量、方法和类可以获得不同的安全级别。 根据我的 C# 经验,有:
public
internal
protected
protected internal
private
现在,我了解了将方法和类设为私有(private)、内部或 protected 用法,但是变量呢?即使我将变量设为私有(private),我也可以使用属性从不同的类调用它。
我一直认为属性是最佳实践。因此,如果我可以使用它,我就不需要通过实例直接调用变量。
是否有任何理由不将变量设为私有(private)?
编辑:我看到有些人在谈论属性时好像它们只不过是 Glorified public variables
快速提醒:公共(public)变量只返回它们的值。使用属性,您可以做更多的事情。例如:
public int AmountOfBooks{
get {
//code to check certain conditions
//maybe trigger an event while we're at it.
//and a few conditionals.
return this.amountOfBooks;
}
set {
//a few conditionals
//maybe trigger an event
this.amountOfBooks = value;
//and I can do even more... I think, never tried this.
}
}
看过我个人资料的人都知道我是一名学生。使用属性作为“美化的公共(public)变量”是我看到很多同学所做的事情。当告诉他们可以这样做时,最常见的回答是:“这是允许的吗?”
最佳答案
当然,在某些情况下拥有公共(public)领域是有意义的。例如,如果您创建的结构仅用于与现有非托管 win32 API 的互操作性。
但如果您要构建常规托管对象模型,则最佳做法是将对象的属性建模为属性,并使用字段作为私下实现公开功能的机制。
更新:我将借此机会指出,我们已尝试在 C# 3.0 中轻松编写仅访问后备存储的属性:
public int Foo { get; set; }
完全一样
private int _Foo;
public int Foo { get { return _Foo; } set { _Foo = value; } }
但更短且更易于阅读。当然,如果您以后需要将其扩展为带有后备存储的长格式,那么这样做并不是重大更改。
你也可以这样做:
public int Foo { get; private set; }
如果你想为类/结构之外的代码创建一个只读属性。
关于c# - 为什么要使用公共(public)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1780513/