String is the most commonly used class in c #. Compared with its usage frequency, string has few operations. There are only about 30 instance methods and more than 10 static methods, it is far from meeting our daily needs.
This article uses the extension method to add the string function. Here are several examples!
First, we extend IsNullOrEmpty, the most common static method of the string class, to the "instance" method:
Public static bool IsNullOrEmpty (this string s)
{
Return string. IsNullOrEmpty (s );
} The following is the call code: 1 public static void Test1 ()
2 {
3 string s = "";
4 bool b1 = string. IsNullOrEmpty (s );
5 bool b2 = s. IsNullOrEmpty ();
6}
Don't underestimate this step. After expansion, we can reduce the time for coding and increase the encoding speed. If you have doubts about this, you can enter the code of lines 4th and lines 5th manually for 100 times (you cannot copy and paste the Code) and try again!
If you need it, you can also extend "IsNotNullOrEmpty ".
Let's take a look at the FormatWith extension.
Public static string FormatWith (this string format, params object [] args)
{
Return string. Format (format, args );
}
Public static void Test2 ()
{
String today = "Today is: {0: yyyy, MM, dd, dd, week ddd}". FormatWith (DateTime. today );
}
It is also very simple. Here we will briefly discuss the efficiency problem. The string. Format function has multiple overloading:
1 public static string Format (string format, params object [] args );
2 public static string Format (string format, object arg0 );
3 public static string Format (string format, object arg0, object arg1 );