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

后端 未结 9 1284
情书的邮戳
情书的邮戳 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

    Use an extension method.

    Ex:

    namespace ExtensionMethods
    {
        public static class MyExtensionMethods
        {
            public static DateTime Tomorrow(this DateTime date)
            {
                return date.AddDays(1);
            }    
        }
    }
    

    Usage:

    DateTime.Now.Tomorrow();
    

    or

    AnyObjectOfTypeDateTime.Tomorrow();
    
    0 讨论(0)
  • 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;
            }
        }
    
    0 讨论(0)
  • 2020-12-04 11:22

    Extension methods are syntactic sugar for making static methods whose first parameter is an instance of type T look as if they were an instance method on T.

    As such the benefit is largely lost where you to make 'static extension methods' since they would serve to confuse the reader of the code even more than an extension method (since they appear to be fully qualified but are not actually defined in that class) for no syntactical gain (being able to chain calls in a fluent style within Linq for example).

    Since you would have to bring the extensions into scope with a using anyway I would argue that it is simpler and safer to create:

    public static class DateTimeUtils
    {
        public static DateTime Tomorrow { get { ... } }
    }
    

    And then use this in your code via:

    WriteLine("{0}", DateTimeUtils.Tomorrow)
    
    0 讨论(0)
提交回复
热议问题