In C#, extension methods enable you to add methods to existing class without creating a new derived class.
Extension methods 要求:
- Define a static class to contain extension method. This class must be visible to client code.
- Implement the extension method like a static method, but add "this" modifier before the first parameter.
- 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);
}
}
}