开发者

Property accessors [duplicate]

This question already has answers here: C# 3.0 auto-properties — useful or not? [closed] (17 answers) C# getters, setters declaration [duplicate] (5 answers) Closed 9 years ago.

Is there any fundamental difference between

public string Name  
{  
  get  
  {  
    return _name;  
  }  
  set  
  {  
    _name = value;  
  }  
} 

and

开发者_开发技巧
public string Name {get; set;}


  1. You can access internal field, in second case it's autogenerated
  2. You can set a breakpoint in VS, in second you cannot.


Nothing fundamental, and you can usually change between them safely.... until something has used the field name (I'm looking at BinaryFormatter here...).

otherwise, no. You can usually change between the, without breaking things, for example to add logic or to add attributes to the field.


Basically there is no fundamental difference, #2 just saves you a lot of lines if you want to do this for 20 properties when you don't need encapsulation upfront but would like to have the option for future.


To external consumers of your class (assuming _name is private), they are the same unless you are using something like BinaryFormatter that uses reflection to store the internal state of your object.

To your class, the major difference is that you don't have access to the field when you use an auto property. This means you can't do some things, such as use the property as a ref or out parameter. For example, if you have a int value and you are reading the default value in your constructor, you can't say Int32.TryParse(s, out Range). You can say Int32.TryParse(s, out _range).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜