老实说,公共变量和公共属性访问器有什么区别?

发布于 2024-11-18 00:09:49 字数 502 浏览 1 评论 0原文

可能的重复:
字段和字段之间有什么区别C# 中的属性
我应该使用公共属性和数据的私有字段还是公共字段?

之间有什么区别:

public string varA;

public string varA { get; set; }

Possible Duplicates:
What is the difference between a field and a property in C#
Should I use public properties and private fields or public fields for data?

What is the difference between:

public string varA;

and

public string varA { get; set; }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦幻的味道 2024-11-25 00:09:49

公共属性访问器为您将来提供了更大的灵活性。

如果您想在设置值时添加验证,只需编写一个非默认设置器即可。您的其他代码都不需要修改。

也可能有一些原因让您想要用代码替换默认的 getter。对于公共变量来说,这可能是一个真正的痛苦。

The public property accessor gives you more flexibility in the future.

If you want to add validation to setting the value, you simply write a non-default setter. None of your other code would have to be modified.

There could also be reasons you'd want to replace the default getter with code. That can be a real pain with a public variable.

明明#如月 2024-11-25 00:09:49

除了其他答案之外,您还可以使用属性来使值只读甚至仅设置:

public int Item { get; private set; } // read-only outside the class. Can only be set privately.

我也遇到过这样的情况:我后来决定要代理一个对象,或者添加 AOP,这基本上需要特性。

In addition to the other answers, you can also use a property to make the value read-only or even set-only:

public int Item { get; private set; } // read-only outside the class. Can only be set privately.

I have also run into situations where I later decide I want to proxy an object, or add AOP, which basically requires properties.

优雅的叶子 2024-11-25 00:09:49

公共属性通过公开的 getter 和 setter 方法访问字段和内部类代码。公共字段直接访问该字段。

使用属性可以提供抽象和设计层(使集合访问器受保护、私有的能力)。

当指定属性并且不存在主体时,编译器将创建一个底层私有字段,用于存储该值。本质上:

private int item = 0;
public int Item {
get { return item; }
set {item = value; }
}

一般来说,我倾向于使用公共暴露变量的属性和私有字段。如果某个字段被多次访问并且速度是至关重要的设计要求,我可能会考虑使用该字段。

Public property accesses fields and internal class code through exposed getter and setter methods. A public field acesses the field directly.

Using propertys offers the potential to provide a layer of abstraction and design (ability to make set accessor protected, private).

When a property is specified and no body present an underlying private field is created by the compiler that is used to store the value against. Essentially:

private int item = 0;
public int Item {
get { return item; }
set {item = value; }
}

In general I tend to use properties for public exposed variables and fields for private. I might consider using a field if that field was accessed many times and speed was a crucial design requirement.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文