Vernacular C #: Features

Source: Internet
Author: User

Anyway, turn around and talk about it.

Http://www.kuqin.com/dotnet/20080628/10196.html

Series Article index: " vernacular C #"

The first thing to say is that maybe some friends who are just in touch with C # often tend to confuse attributes with attributes (Attribute), which is actually two different things. A property is a data field in the object-oriented mind that encapsulates a class, in the form of:

    Public class Humanbase   {       publicstringgetset;}         Public int Get Set ; }         Public int Get Set ; }   }

The fields that appear in the Humanbase class are called properties, and what is the feature (Attribute)?

   [Serializable]   publicclass  humanbase   {        public  Stringgetset;}         Public int Get Set ; }         Public int Get Set ; }   }

In a nutshell, we add a [Serializable] to the previous line of the Humanbase class declaration, which is the feature (Attribute), which means that humanbase can be serialized, which is important for network transmission, but you don't have to worry about how to understand it. How to understand is what we are going to discuss below.

The attributes of C # can be applied to various types and members. The preceding example uses the attribute on a class to be called a "class attribute," and, similarly, a method attribute that precedes a method declaration. No matter where they are used, no matter what the difference between them, the main purpose of the feature is self-description. And because the characteristics can be customized by themselves, not only limited to. NET provides a number of ready-made, so to C # program development brings considerable flexibility and convenience.

Let's use the example of life to introduce the C # feature mechanism.

Suppose you go on a plane one day, you have to go to the airport boarding office to change your boarding pass in advance. A boarding pass is a piece of paper that says which flight, where to fly, and your name, seat number, and so on, which is the feature. It does not require you to physically include these attributes (when humans appear to have no planes yet), just as the Humanbase class above does not have a isserializable attribute, the feature needs only to be added when the class or method needs it, as if you were not always flying in the sky.

When we want to know if Humanbase is serializable, you can pass:

    Static void Main (string[] args)    {        Console.WriteLine (typeof(humanbase). isserializable);             Console.ReadLine ();    }

Getting your boarding pass means you can take off on board legally. But at this point you don't know where you're going to sit, don't worry, the ground crew will drive you over, but how does he know what flight you're on? Obviously it's through your boarding pass. Therefore, the most characteristic feature is self-description .

Since it is the function of description, the purpose is to limit it. It's like the ground is not going to take you to a plane and throw it in front of you, because the descriptive information on the label is limited to the destination, the passenger and the flight, and any errors are considered anomalies. If the previous humanbase does not add the serializable attribute, it cannot be transmitted over the network.

We are going to introduce the method feature, first add a run method to Humanproperty:

[Serializable] Public classHumanpropertybase { Public stringName {Get;Set; }  Public intAge {Get;Set; }  Public intGender {Get;Set; }  Public voidRun (intSpeed ) {            //Running is good for health.        }    }

As long as there is a healthy limbs, the health of the people can run, so to speak, running is a prerequisite, at least the limbs sound, good health. This shows that the disabled and the elderly if running will be problematic. Suppose a Humanbase object represents a oldest old old man, and if he is to be a sparring partner of Liu Xiang, it is directly honorable. How to avoid this situation, we can add a piece of logic code in the Run method, first determine the age size, if less than 2 or more than 60 direct throw exception, but between 2-60 years old also have to use switch to determine whether the speed parameter is appropriate, then the logic is rather bloated. In short, how do you use attributes to indicate that a method cannot be used? OK, here we go:

    [Obsolete ("I"m so old, Don"t kill me! " true )]    publicvirtualvoid Run (int speed )    {         //  Running is good for health.    }

The above describes the use and function of the features, and then we will show you how to improve the flexibility of the program through custom features, if the feature mechanism can only be used. NET offers a few of the features, it is not very enjoyable.

First, the attribute is also a class . Unlike other classes, attributes must inherit from the System.Attribute class , or how the compiler knows who the attribute is and who is the normal class. When the compiler detects that a class is an attribute, it recognizes the information and stores it in the metadata, and that's it, the compiler doesn't care what the feature says, and the feature doesn't do anything to the compiler, just as airlines don't care where each box goes, Only the owner of the box and the porter will care about the details. Let's say we're an airline manager and we need to design the boarding pass we mentioned earlier, so it's easy to see what the main information is:

     Public classBoardingcheckattribute:attribute { Public stringID {Get;Private Set; }  Public stringName {Get;Private Set; }  Public intFlightnumber {Get;Private Set; }  Public intPostionnumber {Get;Private Set; }  Public stringDeparture {Get;Private Set; }  Public stringDestination {Get;Private Set; } }

We simply enumerate these attributes as information on the airline's boarding pass, which, as before, is posted on the humanbase, stating that the person is eligible for boarding. To put it simply, you may have noticed that you have omitted the attribute when using Boardingcheckattribute, and do not worry, because the compiler defaults to adding and then looking for the attribute class. Oh, wait a minute, I suddenly remembered which plane he should be on? Obviously, in this demand, our characteristics have not played its due role, we also do some work, or passengers face a blank ticket will be very confused.

So, we have to add a constructor to this feature because it doesn't just mean boarding, it must contain some necessary information:

     PublicBoardingcheckattribute (stringIdstringNamestringFlightnumber,stringPositionnumber,stringDeparture,stringdestination) {         This. ID =ID;  This. Name =name;  This. Flightnumber =Flightnumber;  This. Positionnumber =Positionnumber;  This. Departure =departure;  This. Destination =destination; }

OK, our passengers will be able to get a formal boarding pass and have a good flight!

   Static voidMain (string[] args) {Boardingcheckattribute Boardingcheck=NULL; Object[] CustomAttributes =typeof(Humanpropertybase). GetCustomAttributes (true); foreach(varAttributeinchcustomattributes) {           if(Attribute isBoardingcheckattribute) {Boardingcheck= attribute asBoardingcheckattribute; Console.WriteLine (Boardingcheck.name+""S ID is "+boardingcheck.id+", he/she wants to"+boardingcheck.destination+" from"+boardingcheck.departure+"By the plane"+Boardingcheck.flightnumber+", his/her position is"+Boardingcheck.positionnumber+".");   }} console.readline (); }
View Code

Vernacular C #: Features (RPM)

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.