C # custom attributes (different from member variables)

Source: Internet
Author: User

Property declaration

public int Age {get; set;}

Functionally equivalent to

private int m_age;

public int Age {
get {return m_age;}
set {m_age = value;}
Here, there is little difference between a property and a member variable. Equivalent to public int age; In the beginning, ignoring limitations, read and Write permissions.
First lazy, write
public int Age {get; set;}

The project is written to a stage, requiring the age value to be valid. Not older than 0.
Then switch into

private int m_age;

public int Age {

get {return m_age;}

set {
if (value < 0) {
Throw an anomaly or something ...
}
M_age = value;
}
}


Or at some point, say age > 30 don't get married or anything.

Then switch into

private int m_age;

public int Age {

get {return m_age;}

set {
if (value < 0) {
Throw an anomaly or something ...
}
M_age = value;

if (value > marryed && = = False) {
To trigger an event ...
}
}
}



Or another stage, saying that age cannot be set externally, only birthdays can be set externally. Age is read-only and is calculated by birthdays.


Then switch into

public int Age {
Get {return this year-year of birthday;}
}

After this modification, all of the original code that was directly set to age will not be compiled. You can simply comment out.That is, in the attribute, we can customize the read and write control of the variable, in the read and write to the internal as far as possible exceptions to the processing out, in reading and writing is relatively safe.

C # custom attributes (different from member variables)

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.