How do I extend a class with c# extension methods?

后端 未结 9 1388
情书的邮戳
情书的邮戳 2020-12-04 10:48

Can extension methods be applied to the class?

For example, extend DateTime to include a Tomorrow() method that could be invoked like:

DateTime.Tomor         


        
9条回答
  •  清歌不尽
    2020-12-04 11:21

    They provide the capability to extend existing types by adding new methods with no modifications necessary to the type. Calling methods from objects of the extended type within an application using instance method syntax is known as ‘‘extending’’ methods. Extension methods are not instance members on the type. The key point to remember is that extension methods, defined as static methods, are in scope only when the namespace is explicitly imported into your application source code via the using directive. Even though extension methods are defined as static methods, they are still called using instance syntax.

    Check the full example here http://www.dotnetreaders.com/articles/Extension_methods_in_C-sharp.net,Methods_in_C_-sharp/201

    Example:

    class Extension
        {
            static void Main(string[] args)
            {
                string s = "sudhakar";
                Console.WriteLine(s.GetWordCount());
                Console.ReadLine();
            }
    
        }
        public static class MyMathExtension
        {
    
            public static int GetWordCount(this System.String mystring)
            {
                return mystring.Length;
            }
        }
    

提交回复
热议问题