Demo Code:
public class program { static void Main (string[] args) { var txt = "Hello"; Console.WriteLine (txt. GetString ()); var inttxt = "123"; Console.WriteLine (Inttxt. GetInt ()); var inttxt1 = "ASD"; Console.WriteLine (Inttxt1. GetInt ()); Console.WriteLine ("234". GetInt ()); Console.WriteLine ("Qwe"). GetInt ()); } } public static class exstring {public static string GetString (this string source) { return source + " Extension method "; } public static int GetInt (this string source) { var outint = 0; if (!string. IsNullOrEmpty (source)) { var result = Int. TryParse (Source,out outint); return outint; } return outint; } }
Code output:
Description
1. Extension methods are static methods that belong to static classes
2, the first parameter of the This keyword, parameter type is the type that needs to be extended
C # Extension methods