问题描述
我有这个枚举代码:
enum Duration { Day, Week, Month };
我可以为此 Enum 添加扩展方法吗?
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");
}
}
}
我认为枚举通常不是最佳选择,但至少这可以让您集中一些 switch/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.
您可以在 Microsft MSDN 此处阅读更多信息.
You can read more here at Microsft MSDN.
这篇关于如何向枚举添加扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!