Two knowledge points about properties in. Net/C #

Source: Internet
Author: User

1: code similar to this:

Public class car
{
Private string name;
Public string name
{
Get {return name ;}
Set {name = value ;}
}
...
}

 

To use automatic attributes:

Public class car
{
Public string name {Get; Set}
...
}

 

The benefit of using property here rather than just using public member variables is:

(1): maintains the encapsulation principle and does not expose public variables to the outside world;

(2): it is easy to add control logic in the future. Or you can close a read or write direction in the get or set;

(3): When metadata is used, the compiler only recognizes attributes but does not recognize member variables. For example, parsechildren (true, "membername") (I think it is online. Actually, I don't understand what it means... Columns here for the moment );

(4): attributes are of special use when binding data (I don't know much about this ...).

 

2: The default value cannot be specified for the automatic attribute. To achieve this effect, you can only initialize it in the constructor!

In addition, to specify automatic attributes, you must specify get; set. The compilation fails.

Public string name {Get; set,

Public string name {Get;} or public string name {set;} is unavailable!

What should I do if I want to automate attributes and read-only or write data?

Write as follows:

Public string name {Get; private set ;}

Public string name {private get; set ;}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.