枚举与功能的方法(组合类/枚举) [英] Enum with methods for functionality (Combine Class / Enum)
问题描述
我可能错过这里一些点,如果是这样的话 - 请包括讨论,因为我的问题的一部分。)
I may miss some sort of point here, if that's the case - please include that discussion as a part of my question :).
这是一个缩短下跌并更名的工作代码示例。所述GetTicks(..)是一个单一的样品,其可以是任何形式的功能性(的制造>值0 10 9
应返回一个特定的Enum a.so)。
This is a shortened down and renamed sample of a working code. The GetTicks(..) is a single sample, which could be any sort of functionality (value of > 0 < 9
should return a specific Enum a.so).
public static class Something
{
public enum TypeOf : short
{
Minute = 2, Hour = 3, Day = 4, ........
}
public static long GetTicks(Something.TypeOf someEnum)
{
long ticks = 0;
switch (someEnum)
{
case Something.TypeOf.Minute:
ticks = TimeSpan.TicksPerMinute;
break;
case Something.TypeOf.Hour:
ticks = TimeSpan.TicksPerHour;
break;
....
}
return ticks;
}
}
// This class is called from anywhere in the system.
public static void SomeMethod(string dodo, object o, Something.TypeOf period)
{
// With the design above
long ticks = Something.GetTicks(period);
// Traditional, if there was a simple enum
if (period == Something.Day)
ticks = TimeSpan.FromDays(1).Ticks;
else if (period == Something.Hour)
ticks = TimeSpan.FromHours(1).Ticks;
}
我们的想法是收集涉及一个枚举,距离越近越好功能枚举本身。枚举的原因职能。此外,我发现很容易和自然来寻找附近的枚举这样的功能。也可以很容易地修改或扩展。
The idea is to collect functionality that concerns a enum, near as possible to the enum itself. The enum is the reason function. Also I find it easy and natural to look for such functionality near the enum. Also it's easy to modify or extend.
的缺点我都有,是我必须声明枚举更明确的 Something.TypeOf
。该设计可能看起来没有标准?如果枚举是在类内部使用也适用。
The drawback I have, is that I have to state the enum more explicit Something.TypeOf
. The design may look no-standard? and would apply if the enum was for internal use in the class.
你会怎么做这个更漂亮?
我试图抽象,基地继承,局部的。他们似乎都不适用。
How would you do this more nice? I tried abstract, base inheritance, partial. None of them seem to apply.
推荐答案
C#枚举不喜欢这个工作。然而,你可以很轻松地实现自己的固定的值:
C# enums don't work well like this. However, you can implement your own "fixed set of values" fairly easily:
public sealed class Foo
{
public static readonly Foo FirstValue = new Foo(...);
public static readonly Foo SecondValue = new Foo(...);
private Foo(...)
{
}
// Add methods here
}
碰巧的是,其中一个例子,我得到了,这是非常相似你的 - 的 DateTimeFieldType
在<一个HREF =https://github.com/nodatime/nodatime相对=nofollow>野田佳彦时间。有时你甚至可能要进行启封类,但保留私有构造 - 它允许你创建子类的只为嵌套类的。 。非常方便的限制继承
As it happens, one example I've got of this is remarkably similar to yours - DateTimeFieldType
in Noda Time. Sometimes you might even want to make the class unsealed, but keep the private constructor - which allows you to create subclasses only as nested classes. Very handy for restricting inheritance.
缺点是,你不能使用开关:(
The downside is that you can't use switch :(
这篇关于枚举与功能的方法(组合类/枚举)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!