Implement and Call a Custom Extension Method
Implement and Call a Custom Extension Method
Author Kaden Kang 康翌
2009-5-14
How to Implement a Custom Extension Method
1. Define a static class to contain the extension method.
2. Create a static Method.
3. Using this keyword to extension method.
Method Extension means developer can add some new method to existent CLR type open rules, not to generate sub class or recompile previous type.
The following code shows how to implement a custom extension method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyExtensionMethod
{
/// <summary>
/// Note: the class must have the static keyword
/// </summary>
public static class MyExtensionMethod
{
/// <summary>
/// Extension method define
/// </summary>
/// <param name="str">string instance</param>
/// <returns>string</returns>
public static string MyString(this string str)
{
return str + " Kaden Kang";
}
}
}
Note: “This” means “string” type extension.
How to Call a Custom extension Method
The following code shows how to call a custom extension method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyExtensionMethod;
namespace ExtensionMethodTest
{
class Program
{
static void Main(string[] args)
{
string str = "test";
Console.WriteLine(str.MyString());
}
}
}
Reference
http://msdn.microsoft.com/en-us/library/bb311042.aspx
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步