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

后端 未结 9 1395
情书的邮戳
情书的邮戳 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();
    

提交回复
热议问题