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

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

    The closest I can get to the answer is by adding an extension method into a System.Type object. Not pretty, but still interesting.

    public static class Foo
    {
        public static void Bar()
        {
            var now = DateTime.Now;
            var tomorrow = typeof(DateTime).Tomorrow();
        }
    
        public static DateTime Tomorrow(this System.Type type)
        {
            if (type == typeof(DateTime)) {
                return DateTime.Now.AddDays(1);
            } else {
                throw new InvalidOperationException();
            }
        }
    }
    

    Otherwise, IMO Andrew and ShuggyCoUk has a better implementation.

提交回复
热议问题