Properties Or Variables in C# [duplicate]

2019-05-19 05:58发布

问题:

Possible Duplicate:
Properties vs. Fields: Need help grasping the uses of Properties over Fields.

I have seen properties and variables in class.

Could you please let me know which scenario we use property and which scenario we use variable.

回答1:

Usually, a property is backed by a variable anyway. Even if you have an automatically implemented property like this:

public string Name { get; set; }

there still a variable behind the scenes. Not all properties are backed by variables (e.g. DateTime.Now) but the vast majority are.

You should virtually always use a property to access data from another type, rather than exposing the variables. (In other words, the variables themselves should be private.) That way you're separating the API of the class from its implementation... exactly how a class stores its data should only concern the class itself.

If you only ever refer to a piece of data within the class itself, you don't really need a property at all, unless you want to perform validation when you're changing it, or something like that.

It's worth thinking carefully before you expose a variable via a property - if you just do it all the time, you lose a certain amount of encapsulation; types shouldn't usually just be collections of data manipulated by other code. They should use the data within them to expose higher-level operations. It's somewhat hard to describe, and I'm not saying that properties are bad per se - just that they can be overused if you're not careful.



回答2:

In general, it is better to create public properties and private variables.

There are few reasons to have public variables.

[An example of where a property is required, is setting an object property and also raising event to notify subscribers of the change].



回答3:

There could be lots of scenarios that there is a difference between using variables and properties. Usually variables are for internal working of a class and a class should not expose variables, in the other words, properties are to be accessed from other classes.

Also some code generation and tools require that you define variables or properties. For example in XAML(WPF and Silverlight) you have to expose variables for dependency properties.

Also since properties are codes being executed for getting or setting a values they even can be used for providing access to something stored in somewhere else, rather than an internal class variable. For example you may define a property that allows binding a piece of UI to a text file's content.



回答4:

You don't `Have' to use a Field instead of a Property, Fields are actually faster at runtime.

But, in general you will want to define instance variables on your classes as Properties. This allows you do to several extra things you can't do with Fields.

  1. Can be Read-Only or Write-Only
  2. Can be included in Interfaces like methods
  3. Can have side-effects.

Interfaces for your classes can make many things easier including testing and maintianence.

public interface IStudentGroup {
  List<string> NameList { get; }
}

Side-effects is one of the most useful features. Say you have a property called Items that contains a collection. You might want this to be automatically initialized if it were null. Eg:

private List<string> namesList;
public List<string> NameList {
  { 
    get { 
      if ( namesList == null ) namesList = new List<string>();
      return namesList;
    }
}


回答5:

Just for completeness I'd like to add (from msdn)

properties should not be computationally complex or produce side effects

So for computational complex operations or situations with side effects, write GetX(), SetX() methods instead of using properties

Property getters should be simple operations without any preconditions. If a getter might throw an exception, consider redesigning the property to be a method. This recommendation does not apply to indexers. Indexers can throw exceptions because of invalid arguments.