为什么使用公共变量?
变量、方法和类可以获得不同的安全级别。 根据我的 C# 经验,有:
公开
内部
受保护
受保护的内部
私人
现在,我了解了将方法和类设为私有、内部或受保护的用途,但是变量呢?即使我将变量设置为私有,我也可以使用属性从不同的类中调用它。
我一直认为属性是最佳实践。因此,如果我可以使用它,我就不需要直接通过实例调用变量。
有什么理由不将变量设为私有吗?
编辑:我看到有些人谈论属性就好像它们只不过是 美化的公共变量
快速提醒:公共变量仅返回其值。有了属性,您可以做更多事情。例如:
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.
}
}
读过我的个人资料的人都知道我是一名学生。我看到很多同学都使用属性作为“美化的公共变量”。当告诉他们可以这样做时,最常见的反应是:“允许这样做吗?”
Variables, methods and classes can receive various security levels.
From my C# experience, there is:
public
internal
protected
protected internal
private
Now, I understand the use of making methods and classes private, or internal or protected, but what about variables? Even if I make a variable private, I can use a Property to call it from a different class.
I've always been thought that Properties are best-practice. So if I can use that, I don't need to call variables directly via an Instance.
Is there any reason not to make a variable private?
EDIT: I see some people talking about Properties as if they are nothing more than Glorified public variables
Quick reminder: public variables return just their value. With properties, you can do more. For instance:
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.
}
}
Those of you who've read my profile know I'm a student. Using properties as "glorified public variables" is something I see a lot of fellow students do. The most common response when telling them they can do this is: "Is that allowed?"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
当然,在某些情况下拥有公共领域是有意义的。例如,如果您创建一个结构体只是为了与现有的非托管 win32 API 进行互操作。
但是,如果您正在构建常规的托管对象模型,则最佳实践是将对象的属性建模为属性,并使用字段作为私下实现公开功能的机制。
更新:我将借此机会指出,我们已尝试在 C# 3.0 中非常轻松地编写一个仅访问后备存储的属性:
与 完全相同,
但更短且更易于阅读。当然,如果您稍后需要将其扩展为具有后备存储的长格式,那么这样做并不是一个重大更改。
您也可以这样做:
如果您想创建一个对类/结构之外的代码只读的属性。
Sure, there are situations in which it makes sense to have a public field. For example, if you are creating a struct solely for interoperability with an existing unmanaged win32 API.
But if you are building a regular managed object model, the best practice is to model the properties of your objects as properties, and use fields as the mechanism that privately implements the publically exposed functionality.
UPDATE: I'll take this opportunity to note that we have tried to make it very easy in C# 3.0 to write a property which simply accesses a backing store:
is exactly the same as
but a lot shorter and easier to read. And of course if you need to expand it into the long form with a backing store later, doing so is not a breaking change.
You can also do this:
if you want to make a property that is read-only to code outside the class/struct.
如果在设置或获取变量时需要执行任何代码,或者如果涉及的 API 存在任何不兼容的更改(如果您将来需要添加此类代码),则属性是最佳实践。
由于后一个子句,在需要此类不兼容更改的语言中“抢先”使用访问器很可能确实有意义(最著名的示例是
getThis
/setThis
Java 中的约定)!但是,当您的语言允许您从公共变量切换到属性(反之亦然)而 API 中没有任何不兼容的更改(例如 C#、Ruby、Python 等)时,当公共访问器(getter)时携带完整的样板文件是愚蠢的和 setter)除了复制到私有变量和从私有变量复制之外什么也不做——即使你确定你的编译器可以优化它们,这样的样板访问器只会无用地使源代码膨胀,并且浪费了一个重要的设计功能,而这个设计功能是此类语言的一部分不错的;-)
Properties are a best practice if there is any code you need to execute when the variable is set or gotten -- or if there is any incompatible-change in API involved should you ever need to add such code in the future.
Due to the latter clause, it most likely does make sense to use accessors "preemptively" in language that would otherwise require such incompatible changes (the best known example being the
getThis
/setThis
convention in Java)!But when your language lets you switch from public variables to properties and vice-versa without any incompatible change in the API (such as C#, Ruby, Python, ...), it's silly to carry around total boilerplate when the public accessors (getter and setter) do nothing except copying to and from a private variable -- even if you're certain your compiler can optimize them away, such boilerplate accessors just bloat the source uselessly, and waste an important design feature that's part of what makes such languages nice ones;-)
我突然想到两个地方可以使用公共字段来
装配体消费者的价值观
基础设施(例如在工作流程中
基础)
Off the top of my head, I can think of two places where I would use public fields
values for consumers of an assembly
the infrastructure (e.g in Workflow
Foundation)
例如,如果您有一个具有属性 id_code 的类。
如果该属性是公共的,我可以使用任何类型的值设置此变量。
如果您将此 id_code 设为私有并创建一个方法来设置它,则可以对 id_code 的格式制定规则。
方法也是如此:
这是第一个简单的例子。
for example, if you had a class with attribute id_code.
if the attribute is public I can set this variable with any type of value.
if you delcare this id_code private and you make a method for set it, you can make a rules about the format of id_code.
And so the method:
this is a first simple example.
是的。例如,将字段标记为受保护允许它直接由派生类使用,派生类在概念上仍然保持面向对象的哲学。
但总的来说,你是对的。通常首选将类的字段标记为私有并将必要的字段公开为属性。这有利于封装、字段验证和代码维护等工作。
Yes. For example, marking a field as protected allows it to be used directly by a derived class which still conceptually maintaining the object-oriented philosophy.
In general, though, you are correct. It is generally preferred to mark fields of a class as private and expose the necessary ones as properties. This facilitates things such as encapsulation, field validation, and code maintenance.
在某些情况下,字段的处理方式与属性不同。标准序列化格式化程序(BinaryFormatter 和 SoapFormatter)将序列化字段,但不会序列化属性。有时可能需要这样做来控制类型的序列化。
There are situations where fields are treated differently than properties. The standard serialization formatters (BinaryFormatter and SoapFormatter) will serialize fields, but not properties. There may be times where this is necessary to control the serialization of your type.
尚未提及的两个原因:
这并不意味着将事物暴露为属性而不是字段没有优势,但字段确实有明确的优势。
Two reasons not yet mentioned:
That doesn't mean there aren't advantages to exposing things as properties rather than fields, but fields do have definite advantages.
如果您的财产说
状态
属于以下性质:公共 int Status {get; set;}
有些人可能只是使用:
公共 int 状态;
If your property say
Status
is of the nature:public int Status {get; set;}
Some people might just use:
public int Status;