C# Extension Methods

In C#, extension methods enable you to add methods to existing class without creating a new derived class.

Extension methods 要求:

  1. Define a static class to contain extension method. This class must be visible to client code.
  2. Implement the extension method like a static method, but add "this" modifier before the first parameter.
  3. The first parameter specifies the type that this extension method operates on.
 using System.Globalization;
using System.Threading; namespace Library
{
public static class StringExtensions
{
//static method
//public static string ConvertToTitleCase(this string source)
//extension method
public static string ConvertToTitleCase(this string source)
{
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo; return textInfo.ToTitleCase(source);
}
}
}

Extension methods call:

Call extension method  like extension method is an instance method on the type.

 namespace Library_Simple
{
//Import extension method namespace
using Library;
class Program
{
static void Main(String[] args)
{
string source = "the return of the king";
string extected = "The Return Of The King"; //static method
//string result = StringExtensions.ConvertToTitleCase(source);
//extension method
string result = source.ConvertToTitleCase(); Assert.IsNotNull(result);
Assert.AreEqual(expected, result);
}
}
}
上一篇:LuManager 2.0.97 设置shopex 手机版waptouch,绑定二级目录


下一篇:ubuntu中rar与unrar用法详解