C # exciting features-expansion method,

Source: Internet
Author: User

C # exciting features-expansion method,

In recent studies, I found a very nice C # feature-expansion method. When I read the book "big talk design model", the book mentioned the following sentence: "Reflection, reflection, and the joy of programmers", I am a newbie, and I have never used reflection so far. I naturally have no idea whether it is really happy or not, but the extension method is quite happy to use!

The extension method enables you to "add" methods to an existing type without creating a new derived type, re-compiling, or modifying the original type using other methods. The extension method is a special static method, but it can be called like the strength method of the extension type. For client code written in C # and Visual Basic, there is no significant difference between calling an extension method and calling a method actually defined in the type.

-- Description of the Extension Method in MSDN

When I first started to learn C #, I often encountered various situations that needed state conversion. At that time, the Code was often Convert. toXX (); at that time, I envy the String class and can directly call the ToString method, saving time and effort, and the code looks very beautiful. Then I learned to Convert it. toXX () is packaged into a method. The code is not so redundant, but it is still not very beautiful and time-consuming and laborious. Until today, I have discovered this exciting feature in C, finally, there is a perfect solution to this problem!

Let's take a look at the basic syntax:

Public static return type method name (this requires class name variable name,) {return ;}

Example:

First, we write a class like this:

namespace ExtensionMethods{    public static class ExtensionMethods    {        public static int ToInt(this string s)        {            return Convert.ToInt32(s);        }    }}

Then, you only need to reference the namespace of the class in another class, so that you can easily use the extension method we have written for type conversion:

using ExtensionMethods;namespace xxx{    public static class xxxx    {        public static int Test()        {            int i = "123".ToInt();        }    }}

How is it? Is it really cool!

Don't worry, how can we meet our needs in this way, and we will continue to optimize it.

1. You need to reference the namespace every time, which is a waste of time and energy.

Solution: Put the extension method directly under the namespace of the type

The above code is as follows:

namespace System{    public static class ExtensionMethods    {        public static int ToInt(this string s)        {            return Convert.ToInt32(s);        }    }}

In this way, after adding this class to the project, the String can be converted to Int at any position of the project.

But is that enough? No! No! No !, For example, what if the String parameter is not of the numeric type?

2. If the input String cannot be converted to a number, an error is returned.

Solution: add another parameter as the default value. If the conversion fails, the default value is returned.

The Code is as follows:

public static int ToInt32(this string s, int def = default(int)){    int result;    return Int32.TryParse(s, out result) ? result : def;}

According to the above idea, we can package a class that contains various common type conversions. When writing a program, we only need to directly add this class, so that we can easily perform various hexadecimal conversions.

The following describes a self-used convertclass convert.zip.

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.