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 out fields that are not properly used.Code. Here, we can declare the field as private and then declare the accessor method.

 
ClassTest
{

PrivateStringName;
Public VoidSetname (StringValue)
{
Name = value;
}
Public StringGetname ()
{
ReturnName;
}

}

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.

ClassTest
{

PrivateStringName;
Public StringName {
Get{ReturnName ;}
Set{If("Dog Left"= Value) {console. writeline ("System Crash, throwing an exception");Return;} Name = value ;}
}

}

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

If you only create attributes to encapsulate a supported field, C # also provides a simpler syntax called automatically implemented attributes.(Automatically implemented property, or AIP ). Like this

 
ClassTest
{
Public IntAge
{
Get;
Set;
}
}

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 IntAge
{
[Compilergenerated]
Get
{
IntNum;
Num =This. <Age> K _ backingfield;
Label_0009:
ReturnNum;
}
[Compilergenerated]
Set
{
This. <Age> K _ backingfield = value;
Return;
}
}

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.

Everything is good or bad, soWhat 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 them.ProgramWhen to obtain or set this attribute. You can set the breakpoint manually. If you don't believe it, try it.

The AIP function applies to the entire attribute: either used or not usedThis means that if you explicitly implement get, set must also be explicitly implemented, 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 ); // Attribute, indexer, or dynamic member cannot be passed as an out or ref Parameter
Console. readkey ();
}
Static Void Some ( Out Int Age)
{
Age = 10 ;
}
}

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:

ClassTest
{
Public IntAge
{
Get{ReturnAge ;}
Protected Set{If(Value <0) Console. writeline ("Age error!");Else{Age = value ;}}
}
IntAge;
}

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,C # syntax requirements must specify the least restrictive type of accessibility for the attribute itselfThen, you can select only one of the two access types that has a large application restriction. In the previous example, the property itself is public, and the Set accessors are protected (the limit is greater than public ).

 
ClassTest
{
Private IntAge
{
Get{ReturnAge ;}
Protected Set{If(Value <0) Console. writeline ("Age error!");Else{Age = value ;}}//Compilation fails.
}
IntAge;
}

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.