Using the Silverlight Extension Methods feature, we can extend the basic class and add some Methods to the basic class. The added Methods can be called in the same way as the original Methods of the basic class, which is quite convenient. Let's look at an example. When using DateTime, you often need to obtain the total number of milliseconds since January 1,. However, DateTime in C # does not provide this function. The following uses Extension Methods as an example to describe the Extension Methods feature. The Code is as follows.
Namespace Huizhang212
{
/// <Summary>
/// Use the Extension Methods feature to extend the DateTime base class
/// </Summary>
Public static class HuiExtensions
{
/// <Summary>
/// DateTime Extension function
/// Obtain the total number of milliseconds since January 1
/// </Summary>
/// <Param name = "dt"> </param>
/// <Returns> </returns>
Public static long GetTime (this DateTime dt)
{
DateTime d1970 = new DateTime (1970, 1, 1 );
Return (dt. Ticks-d1970.Ticks)/10000;
}
}
/// <Summary>
/// Test case
/// </Summary>
Public class TestCase
{
Public static void Test ()
{
// Obtain the number of milliseconds
DateTime now = DateTime. Now;
Long time = now. GetTime ();
}
}
}
Through the above example, you can easily understand the usage of the Extension Method feature. In short, Extension Method is a special Static Method defined in Static Class. It is a special static method because it can be called not only like a normal static method, but also through an instantiated object.