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

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

    You cannot add methods to an existing type unless the existing type is marked as partial, you can only add methods that appear to be a member of the existing type through extension methods. Since this is the case you cannot add static methods to the type itself since extension methods use instances of that type.

    There is nothing stopping you from creating your own static helper method like this:

    static class DateTimeHelper
    {
        public static DateTime Tomorrow
        {
            get { return DateTime.Now.AddDays(1); }
        }
    }
    

    Which you would use like this:

    DateTime tomorrow = DateTimeHelper.Tomorrow;
    

提交回复
热议问题