【. NET deep Breathing "basics: Custom Type conversions

Source: Internet
Author: User

As usual, the old week before beginning to brag, first tell the story, this is a friend put forward suggestions, old TMD write technology what great, everyone will write. Later, the old weeks to think about, and indeed, code who will not write, can write to have taste and sentiment, it is not easy to do. So, the old week accepted the advice of the friend.

Have the first into the work of the younger brothers and sisters often complain, why, because often scolded by the old staff, scolded by the boss. It seems that the things I do are always wrong, so I feel very hurt and sad.

The old week here must remind you that the lad should be strong, and the younger sisters should not be too desperate, do not do stupid things. West Lake Landscape is very beautiful, "want to West West Lake, Xishi is always suitable", but if someone jumped the West Lake suicide, really blot, destroy the natural heaven. You do not want to be this kind of ages, and want to think more about the parents, raise you so big, if you feel this kind of suicidal behavior is also filial piety, then you go to die, the old week do not stop you.

The first into the workplace, who is not every day is scolded, thinking back old week, often in the morning to the office, open the computer, and then looked up, the wall of cardboard listed on the old week last month's top ten counts, the mother, written like a court verdict, that posture, almost to eat people's posture.

As for the old staff, usually by the boss's anger, now you come in, do not take your vent to find who to go. One of the scariest things about people is emotional slavery, especially workplace stress. And more frightening than this is that modern people are really in many places than the ancients, now the person encountered the things that are not good, do not know how to dissolve and adjust, or the self-destruction, or indulge in wine, or addicted to online games. The fundamental, is the spirit of the world is too blank, usually do not read more books, others hole old man said, Slim Zi flat world, you, even Slim did not do well, but also blowing what? A house does not sweep, why sweep the world?

When the old weeks were scolded, standing there listening, after listening to, in the heart without any feeling, go home to read a few poems at night to forget all the day things. In the workplace, you should have this skill.

Remember the old week to do the most fierce, but also the most glorious thing, about the beginning of 2011, one day to the office, accustomed to look up to see cardboard, found a few more difficult to read a few words-"carelessness." I knew the manager was talking about me again. After work at noon, I went to the other side of the road to find my friend, where she opened a children's calligraphy and painting training. I went to her there to find rice paper and a brush, and then wrote four characters-"hardships", and then invited her to eat as a thank you.

In the afternoon after work back to the office, I just wrote a few block letters directly on the manager wrote a few ugly words above, and then continue to work.

The next morning, the manager came in and saw the characters I wrote, I said in my ear: "You son, really have you." "At that time, the old week also want to change the environment, so the old week to the manager promised, the recent project completed, after writing various documents, for the back of the people take over, very free and easy to leave the company."

Lao Zhou always thought that the manager should be angry that day. Who thought, a few years later, in May 2015, I ran into a manager and a couple of old colleagues at my relatives ' wedding. I was very frank and asked the manager: "That thing, you were very angry at that time?" The manager put down his chopsticks and said, "No, it's amazing." Your words are still there, you can come to the office when you are free. "Then we talked about a bunch of gossip, like how it education, how to train new employees, and so on." I feel that the manager is very friendly to me now, and the exact opposite of a few years ago.

The story is finished, the old week is just telling the truth, as for the old week to do the right, your own reference it.

=======================================================

Today say a basic knowledge, I remember, my bad book "Proficient in C #" introduced the content of custom type conversion, the title is a bit exaggerated, the old week did not like the name, but the publishers like, I can not.

Implementing a custom type conversion can be resolved by overloading the operator. There are two ways of converting:

1. Implicit conversion: Just as a subclass instance can be directly assigned to a base class variable, it does not need to write any casts, and the type can be converted automatically by assigning values.

2. Explicit conversion: You must write the cast manually to complete the conversion of the type. such as int x = (int) DV;

OK, let's use an example to speak, first of all, an implicit conversion.

Let's say I define a product class that represents information for one of the products.

     Public class Product    {        publicintgetset;}          Public string Get Set ; }          Public float Get Set ; }    }

I want to implement: You can implicitly convert a product class to a string type. The conversion operator can be overloaded in a type.

         Public Static Implicit operator string (Product p)        {            return $" Product id = {P.proid}, Product name = {P.proname}, Product size = {P.prosize}" ;        }

Similar to ordinary operator overloading, it is declared as public, static, because the operator is of the type of operation and is not set for an instance. To implement an implicit conversion, you need to add the implicit keyword, where the conversion operator is actually the target type to be converted, here is a string, and the operand that participates in the operation is the product instance.

Below, together to witness a miracle.

        Static voidMain (string[] args) {Product PRD=NewProduct (); Prd. Proid=1001; Prd. Proname="Shanhuo Bike"; Prd. Prosize=1.35f; //implicitly converted to a string            stringstr =PRD; //OutputConsole.WriteLine (str);        Console.read (); }

The results are as follows.

Under normal circumstances, the product instance cannot be converted to string, but because of the operator overloading that defines implicit conversions above, it makes this assignment possible.

String str = PRD;

If you use an explicit conversion, you must explicitly specify the cast when you use it.

Suppose a work class, the code is as follows:

 public  class   work { public  int  Num1 {
   
    get ; 
    set         
     public  int  Num2 {get ; set          public  static  explicit  operator  int   (work W) { return  w.num1 * W.        Num2; }    }
   

The explicit conversion overload is almost the same as the previous implicit conversion, except that the implicit keyword is replaced with the explicit keyword. You can test it below.

            New Work ();             5 ;             7 ;             // to cast            when assigning a value int n = (int) wk;            Console.WriteLine ($" calculation result: {n}");

Similarly, under normal circumstances, the work class is a composite type, and it is not possible to cast to an int value, but because there is a custom transformation in the class, the conversion can be done using casts.

In fact, there are many types in. NET libraries that also define these transformations, such as in WPF, where the Duration property of an animated timeline object can be implicitly converted by a timespan.

Don't underestimate this basic knowledge point, experience has shown that this stuff is very useful in practical applications.

Sample code Download

【. NET deep Breathing "basics: Custom Type conversions

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.