C # No parameter attribute

Source: Internet
Author: User

 

Let's discuss whether there is a need for C # No parameter attribute?

Never expose fields of the type. One of the important principles of object-oriented design and programming is Data encapsulation. If fields of the Public type are exposed, it is easy to write code that does not properly use fields. Here, we can declare the field as private and then declare the accessor method.

Class test

{

Private string Name;

Public void SetName (string value)

{

Name = value;

}

Public string GetName ()

{

Return Name;

}

}

Copy code

It is so easy to implement read-only or write-only, and you just need to implement the method of an index. You can also mark the Setname method as protected to only allow modification of the derived class. If you are smart, you also find the disadvantages of the above practice. First, you must implement additional methods, so more code will be generated. Second, if you must call the method during the call, A field name cannot be referenced directly. Fortunately, C # provides us with a mechanism called property, which relieves the impact of the first defect and eliminates the second one.

Class test

{

Private string name;

Public string Name {

Get {return name ;}

Set {if ("dog left" = value) {Console. WriteLine ("system crash, throwing an exception"); return ;}name = value ;}

}

}

Copy code

The attribute can be marked with any accessable modifier. Attributes with the same name cannot be defined.

If you create an attribute to encapsulate a supported field, C # also provides a simpler syntax called the Automatically Implemented attribute (AIP ). Like this

Class test

{

Public int Age

{

Get;

Set;

}

}

Copy code

If you declare an attribute without the get/set implementation, C # automatically declares a private field for you. The original code is as follows:

Public int Age

{

[CompilerGenerated]

Get

{

Int num;

Num = this. <Age> k _ BackingField;

Label_0009:

Return num;

}

[CompilerGenerated]

Set

{

This. <Age> k _ BackingField = value;

Return;

}

}

 

Copy code

What are the advantages of automatically implemented attributes compared with directly declaring a public Age field? There is an important difference between the two: using an automatically implemented attribute (AIP) means that an attribute has been created and the get/set method is called when accessing this attribute. If one day you decide to implement the AIP get/set by yourself and do not accept the default Implementation of the compiler, no code accessing this attribute will need to be re-compiled. If it is a public Age field, if you change it to a property, then all the code accessing this field needs to be re-compiled.

If everything is good or bad, what are the inconveniences of AIP:

1. If the field declaration syntax is used, it can contain the initialization part. If AIP is used, it will not work. Each AIP must be initialized as shown in the deployment constructor.

2. the Field Names supported by AIP are determined by the compiler. This field name may be changed every time you re-compile it. In this way, as long as there is an AIP, the type of instances cannot be deserialized. Do not use the AIP function in any type that you want to serialize or deserialize.

3. You cannot add breakpoints in AIP get/set, so it is difficult to detect when the program gets or sets this attribute. You can set the breakpoint manually. If you don't believe it, try it.

The AIP function is applied to the entire attribute: either used or not used. This means that if get is implemented explicitly, set must be implemented explicitly, and vice versa.

 

Attributes look similar to fields, but they are essentially methods. The difference between attributes and fields is as follows:

1. attributes can be read-only or write-only (get/set accessors), but fields are always readable and writable.

2. Attribute methods may throw an exception and field access will not throw.

3. Attributes cannot be passed to methods as out or ref parameters, and fields are acceptable.

Class Program

{

Public int Age

{

Get {return 3 ;}

Set {}

}

Int age;

Static void Main ()

{

Var t = new {name = "XiaoBai", age = 22 };

Test tt = new test ();

// Tt. Name = "dog left ";

Program p = new Program ();

Some (out p. age );

Some (out p. Age); // attributes, indexer or dynamic members cannot be passed as out or ref parameters.

Console. ReadKey ();

}

Static void some (out int age)

{

Age = 10;

}

}

Www.2cto.com

4. Attribute methods may take a long time to execute, and field access is completed immediately.

5. attribute methods may require additional memory or return an incorrect reference pointing to something that is not part of the object state. In this way, the modification to the returned object does not work on the original object. On the contrary, the query field always returns a correct reference. What it points to is guaranteed to be part of the original object state. When a copy attribute is returned, it is very confusing.

If you carefully study the differences between attributes and fields, you will find that attributes are useful only in a few cases. The only benefit of a property is that it provides a simplified syntax. Compared with calling a common method (a method that is not a property), a property will not only improve the Code performance, but also impede the understanding of the Code.

The accessibility of the property accessors:

We sometimes want to specify an accessibility for the get accesser and another accesser for the set accesser:

Class test

{

Public int Age

{

Get {return age ;}

Protected set {if (value <0) Console. WriteLine ("age error! "); Else {age = value ;}}

}

Int age;

}

Copy code

As mentioned above, the Age attribute is declared as public, meaning that the get accesser method is public and can be accessed by all Code. However, note that the set accesser method is declared as protected, it can only be called from the internal defined code of test, or from the code of the derived class of test.

When defining an attribute, if two access methods need to have different accessibility, the C # syntax requires that the attribute itself be specified with the least restrictive access, then, you can select only one of the two types of access that is restricted by the application. In the previous example, the property itself is public, and the set accessors are protected (the limit is greater than public ).

Class test

{

Private int Age

{

Get {return age ;}

Protected set {if (value <0) Console. WriteLine ("age error! "); Else {age = value ;}// compilation is not allowed here

}

Int age;

}

From the little white

Related Article

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.