c# The use of extension methods

In layman's terms, the extension method is to add one or more methods to these types such as String, Int, DateTime, DataRow, DataTable, etc., without the need to modify or compile the code of the type itself.

 

Example 1: Format and display time type variables

Conventional writing:

DateTime now = DateTime.Now;
string time = now.ToString("yyyy-mm-dd hh:mm:ss");

Extension method:

Define an extension method

using System;

namespace DB.MySql
{
    public static class ExtHelper
    {
        /// <summary>
        /// 日期格式化
        /// </summary>
        public static string DateToString(this DateTime dt)
        {
            return dt.ToString("yyyy-mm-dd hh:mm:ss");
        }
    }
}

The above code indicates that an extension method is defined for the DateTime type, and the method name is DateToString.

When you want to format a variable of the time type in the project, enter "now." and you can see that there is a DateToString() method that is automatically prompted, which can be called directly like the instance method of the date type itself, which is very convenient of.

 

Example 2: Convert a string to a number

Conventional writing:

        /// <summary>
        /// 字符串转数字
        /// </summary>
        public static int StrToInt(string s)
        {
            int id;
            int.TryParse(s, out id);//这里当转换失败时返回的id为0
            return id;
        }

transfer:

string s = "2";
int i = StrToInt(s);

 

 Extension method:

        /// <summary>
        /// 将字符串转换为Int
        /// </summary>
        /// <param name="t"></param>
        /// <returns>当转换失败时返回0</returns>
        public static int StrToInt(this string t)
        {
            int id;
            int.TryParse(t, out id);//这里当转换失败时返回的id为0
            return id;
        }

transfer:

string s = "2";
int i = s.StrToInt();

 

Example 3: Determine whether a date is within the range of two dates (expansion method with parameters)

Extension method:

        /// <summary>
        /// 此时间是否在此范围内
        /// </summary>
        /// <param name="t"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public static bool IsRange(this DateTime t, DateTime startTime, DateTime endTime)
        {
            if ((startTime - t).TotalSeconds > 0)
            {
                return false;
            }

            if ((endTime - t).TotalSeconds < 0)
            {
                return false;
            }

            return true;
        }

Call: Determine whether t1 is within the time range of dtStart and dtEnd

DateTime t1 = DateTime.Now;
DateTime dtStart = DateTime.Now.AddDays(-1);
DateTime dtEnd = DateTime.Now.AddDays(1);
bool b = t1.IsRange(dtStart,dtEnd);

 

From the above three simple examples, we can see that the extension method is very practical in actual development. Here is a summary of the extension method:

Elements of the extension method:

1. This method must be a static method (method uses static modification)
2. This method must be placed in a static class (class uses static modification)
3. The first parameter of this method must start with this, and specify that this method is Which type to extend from (DateTime, string, etc.)

Features of the extension method:

1. From which type the extension method is extended, it must be a variable of this type. Other types cannot be used. An instance of an extension from the DateTime type can only be a variable of the DateTime type. Out ()
2. In the extension method The parameter after this does not belong to the parameter of the method. Examples 1 and 2 are both parameterless extension methods. The DateTime dt after this example indicates that the extension method extends from the date type. Instance three is a parameterized extension method, startTime and endTime are two actual parameters
. 3. If the extension method and the instance method have the same signature, the instance method will be called first
. 4. The method extended from the parent class can be directly used by the object of the subclass Use
5. Extension methods on the interface, which can be used directly by the objects of the implementation class.
6. The extension method is finally compiled by the compiler into: static class. Static method (), in this case now.DateToString() will eventually be Compile into DateHelper.DateToString(now), this is its essence

 

Guess you like

Origin blog.csdn.net/liangmengbk/article/details/112393864