如何添加扩展方法枚举 [英] How to add extension methods to Enums

查看:154
本文介绍了如何添加扩展方法枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的枚举代码:

enum Duration { Day, Week, Month };



我可以添加一个扩展方法,此枚举?

Can I add a extension methods for this Enum?

推荐答案

根据这个的网站

扩展方法提供了一种方法来写的方式其他人在你的团队实际上可能发现和利用现有类的方法。鉴于枚举类是像任何其他应该不会太令人惊讶的是,你可以扩展它们,如:

Extension methods provide a way to write methods for existing classes in a way other people on your team might actually discover and use. Given that enums are classes like any other it shouldn’t be too surprising that you can extend them, like:

enum Duration { Day, Week, Month };

static class DurationExtensions {
  public static DateTime From(this Duration duration, DateTime dateTime) {
    switch duration {
      case Day:   return dateTime.AddDays(1);
      case Week:  return dateTime.AddDays(7);
      case Month: return dateTime.AddMonths(1);
      default:    throw new ArgumentOutOfRangeException("duration")
    }
  }
}

我觉得枚举不是一般的最佳选择,但至少这可以让你集中一些开关/ IF处理和抽象他们离开一点,直到你可以做的更好的东西。记住要检查中值的范围了。

I think enums are not the best choice in general but at least this lets you centralize some of the switch/if handling and abstract them away a bit until you can do something better. Remember to check the values are in range too.

您可以阅读更多的这里在MSDN的Microsft

You can read more here at Microsft MSDN.

这篇关于如何添加扩展方法枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆