[英]Why can't a field itself have getters/setters like properties do?
I'm a C# beginner, so easy explanations are greatly appreciated.我是 C# 初学者,非常感谢简单的解释。 I was learning about properties, and got this question: properties give custom access logic to fields, but why can't the field itself contain its getter/setter?
我在学习属性时遇到了这个问题:属性为字段提供自定义访问逻辑,但为什么字段本身不能包含它的 getter/setter? In other words, is there a reason why we can't get rid of Example and write custom get/setters under example(field)?
换句话说,我们不能摆脱 Example 并在 example(field) 下编写自定义 get/setter 有什么原因吗?
I could not find other posts that answer my question.我找不到其他可以回答我问题的帖子。
class MyClass
{
private int example = 5;
public int Example
{
get;
private set;
}
// here, this Example property only acts as a gateway for example.
// why is it not possible for the field 'example' to contain the
// get/set?
}
Property is an interface to Class, and not always is about storing data, you can always make the variable public member and will work perfectly like property, but the property has its own main job to work as an interface for that value with other classes.属性是类的接口,并不总是与存储数据有关,您始终可以使变量成为公共成员,并且可以像属性一样完美地工作,但是属性有自己的主要工作,可以作为该值与其他类的接口。 While in many cases the property just works as public parameters, it is not always meant to be used in that way.
虽然在许多情况下该属性仅用作公共参数,但并不总是以这种方式使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.