C# 我应该对数据使用公共属性和私有字段还是公共字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1277572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:35:46  来源:igfitidea点击:

Should I use public properties and private fields or public fields for data?

c#.netcoding-styleproperties

提问by Callum Rogers

In much of the code I have seen (on SO, thecodeproject.com and I tend to do this in my own code), I have seen public properties being created for every single private field that a class contains, even if they are the most basic type of get; set;like:

在我看到的大部分代码中(在 SO、thecodeproject.com 上,我倾向于在我自己的代码中这样做),我已经看到为类包含的每个私有字段创建了公共属性,即使它们是最多的get; set;喜欢的基本类型:

private int myInt;
public int MyInt 
{
     get { return myInt; }
     set { myInt = value }
}

My question is: how does this differ from:

我的问题是:这与以下有何不同:

public int MyInt;

and if we should use properties instead of public fields why should we use them in this specific case? (I am not talking about more complex examples where the getters and setters actually do something special or there is only one get or set (read/write only) rather than just returning/setting a value of a private field). It does not seem to add any extra encapsulation, only give a nice icon in IntelliSense and be placed in a special section in class diagrams!

如果我们应该使用属性而不是公共字段,为什么要在这种特定情况下使用它们?(我不是在谈论更复杂的例子,其中 getter 和 setter 实际上做了一些特殊的事情,或者只有一个 get 或 set(只读/写),而不仅仅是返回/设置私有字段的值)。好像没有添加任何额外的封装,只是在IntelliSense中给出一个漂亮的图标,放在类图中的一个特殊部分!

采纳答案by Johnno Nolan

See this article http://blog.codinghorror.com/properties-vs-public-variables/

见这篇文章http://blog.codinghorror.com/properties-vs-public-variables/

Specifically

具体来说

  • Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
  • You can't databind against a variable.
  • Changing a variable to a property is a breaking change.
  • 反射在变量和属性上的工作方式不同,所以如果你依赖反射,使用所有属性会更容易。
  • 您不能对变量进行数据绑定。
  • 将变量更改为属性是一项重大更改。

回答by Noon Silk

There are many reasons why.

原因有很多。

Mainly:

主要是:

  • You can do some other functions when the variable is set
  • You can prevent setting and provide only get
  • Some 'things' only work on properties (DataBinding, for example)
  • You can hide the implementation of the property [perhaps it is a ViewState variable, in ASP.NET).
  • 设置变量后可以做一些其他的功能
  • 您可以阻止设置并只提供获取
  • 某些“事物”仅适用于属性(例如,DataBinding)
  • 您可以隐藏属性的实现[也许它是一个 ViewState 变量,在 ASP.NET 中)。

回答by PatrikAkerstrand

Well it does make a difference. Public data can be changed without the object instance knowing about it. Using getters and setters the object is always aware that a change has been made.

那么它确实有所作为。可以在对象实例不知道的情况下更改公共数据。使用 getter 和 setter 对象始终知道已进行更改。

Remember that encapsulating the data is only the first step towards a better structured design, it's not an end-goal in itself.

请记住,封装数据只是实现更好结构化设计的第一步,它本身并不是最终目标。

回答by Dominic Rodger

The point is - what if further down the line you want to make sure that every time myIntis referenced something special happens (a log file is written to, it's changed to 42 etc)? You can't do that without getters and setters. Sometimes it's wise to program for what you might need, not what you need right now.

关键是 - 如果您想确保每次myInt引用时都会发生一些特殊的事情(写入日志文件,将其更改为 42 等),该怎么办?如果没有 getter 和 setter,你就无法做到这一点。有时,根据您可能需要的内容而不是您现在需要的内容进行编程是明智的。

回答by Max Schmeling

Three reasons:

三个原因:

  1. You cannot override fields in subclasses like you can properties.
  2. You may eventually need a more complex getter or setter, but if it's a field, changing it would break the API.
  3. Convention. That's just the way it's done.
  1. 您不能像覆盖属性那样覆盖子类中的字段。
  2. 您最终可能需要更复杂的 getter 或 setter,但如果它是一个字段,更改它会破坏 API。
  3. 习俗。这就是它的方式。

I'm sure there are more reasons that I'm just not thinking of.

我敢肯定还有更多我没有想到的原因。

In .Net 3.x you can use automatic properties like this:

在 .Net 3.x 中,您可以使用这样的自动属性:

public int Age { get; set; }

instead of the old school way with declaring your private fields yourself like this:

而不是像这样自己声明你的私人领域的老派方式:

private int age;

public int Age
{
    get { return age; }
    set { age = value; }
}

This makes it as simple as creating a field, but without the breaking change issue (among other things).

这使它像创建一个字段一样简单,但没有破坏性更改问题(除其他外)。

回答by R4cOOn

Actually, if you're using Silverlight, you'll realise that fields cannot be set a static resources and thus you'll have to use a property (even to access a const).

实际上,如果您使用 Silverlight,您会意识到字段不能设置为静态资源,因此您必须使用属性(甚至访问const)。

I've realised that when I tried to federate the region names I use in Composite Guidance (PRISM).

我已经意识到,当我尝试联合我在 Composite Guidance (PRISM) 中使用的区域名称时。

However, that's just a language limitations and apart from static/constfields I alsways use properties.

然而,这只是一种语言限制,除了static/const字段我总是使用属性。

回答by rayimag

The idea is you should not accidentally/unintentionally change the value of a class private field outside. When you use get and set, that means you are changing the class private field intentionally and knowingly.

这个想法是您不应该意外/无意地更改外部类私有字段的值。当您使用 get 和 set 时,这意味着您有意且有意地更改类私有字段。

回答by agnieszka

When you create private field nameand a simple public property Namethat actually gets and sets the namefield value

当您创建私有字段名称和一个简单的公共属性Name 时,它实际获取和设置名称字段值

public string Name
{
   get { return name; }
}

and you use this property everywhere outside your class and some day you decide that the Nameproperty of this class will actually refer to the lastNamefield (or that you want to return a string "My name: "+name), you simply change the code inside the property:

并且您在类之外的任何地方都使用此属性,并且有一天您决定该类的Name属性实际上将引用lastName字段(或者您想返回一个字符串“My name:”+name),您只需更改属性内的代码:

public string Name
{
   get { return lastName; //return "My name: "+name; }
}

If you were using public field nameeverywhere in the outside code then you would have to change nameto lastNameeverywhere you used it.

如果您在外部代码中的任何地方都使用公共字段名称,那么您必须在任何使用它的地方将名称更改为lastName

回答by Myra

Setting a value into a private field only changes that field,but making them in property you can handle another arguments for example,you can call a method after setting a value

将值设置为私有字段只会更改该字段,但将它们设置为属性您可以处理其他参数,例如,您可以在设置值后调用方法

private string _email;
public string Email
{
    get
    {
        return this._email;
    }
    set
    {
        this._email = value;
        ReplaceList(); //**
    }
}




回答by Russell Steen

It... depends?

这取决于?

I always use getters & setters, since they created this shortcut:

我总是使用 getter 和 setter,因为他们创建了这个快捷方式:

public int Foo { get; set; }

公共 int Foo { 得到;放; }

At compile time it is translated. Now you can't get fancy with it, but it is there, and if you need to get fancy you just spell it out later.

在编译时它被翻译。现在你不能喜欢它,但它就在那里,如果你需要喜欢它,你可以稍后把它拼出来。

However public, private, protected... it's all a matter of who you want to be able to tweak the data. We use inheritance a lot and this is a very common method for us, so that only chidren can edit certain properties.

无论是公共的、私有的、受保护的……这都是您希望能够调整数据的人的问题。我们经常使用继承,这对我们来说是一种非常常见的方法,因此只有孩子才能编辑某些属性。

protected _foo;  
public Foo  
{  
    get { return _foo; }
} //lack of set intentional.