简体   繁体   English

为什么字段本身不能像属性那样具有 getter/setter?

[英]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.

相关问题 为什么自动属性需要getter和setter? - Why do automatic properties require both getters AND setters? 为什么 DependencyProperties 需要外观属性/getter/setter - Why do DependencyProperties need facade properties/getters/setters 这个代码有效吗? 我可以在 class 中拥有一个没有公共 getter 和 setter 的私有字段吗? - Is this code valid? Can I have a private field in a class without public getters and setters? 为什么我不能将自动实现的 getter 和 setter 与 List 一起使用? (统一,C#) - Why can't I use automatically implemented getters and setters with a List? (Unity, C#) 如何在没有成对的getter的类上对setter进行单元测试? - How to unit test setters on classes that do not have paired getters? C#属性:在getter或setter中验证? - C# Properties: Validation in getters or setters? 使用DTO类的简单获取器/设置器查找属性 - Finding properties with simple getters/setters of a DTO class 如何创建一个忽略没有setter的属性的Fluent NHibernate约定 - How can I create a Fluent NHibernate Convention that ignores properties that don't have setters C# 如何允许接口具有带有 getter/setter 的成员变量? - How can C# allow interface's to have member variables with getters/setters? 使用反射,如何检测具有setter的属性? - Using reflection, how do I detect properties that have setters?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM