比较Enum和Class,最佳实践?

问题描述 投票:2回答:2

在我的程序中,我将Enum划分为“Group”(为了清晰而重命名):

public enum FlowSteps
{
    GROUP1_Step1,
    GROUP1_Step2,
    GROUP2_Step1,
    GROUP1_Step2,
    ...
}

然后我的观点我检查当前步骤如下:

FlowSteps currentStep = ...;
if (currentStep == GROUP1_Step1) { //Do something }

现在,我想重构一下我并不喜欢的这种分组,而且我还是喜欢这样的东西:

public class FlowSteps
{
    public enum GROUP1
    {
        Step1,
        Step2
    }

    public enum GROUP2
    {
        Step1,
        Step2
    }
 }

更清楚,但现在我无法通过以下方式比较我当前的步骤:

FlowSteps currentStep = ...;
if (currentStep == FlowSteps.GROUP1.Step1) { //Do something }

关于如何保持我的Enum的这种分组以及能够在不增加太多复杂性的情况下比较该类的任何建议?

你会怎么做?

c# enums
2个回答
3
投票

我认为枚举列表不是正确的方法。我会使用一组带有整数的类,使它们产生唯一的数字。

public static class FlowSteps
{
    private const int GroupSize = 100;

    public static class Group1
    {
        private const int GroupId = 1;

        public const int Step1 = FlowSteps.GroupSize * GroupId + 1;
        public const int Step2 = FlowSteps.GroupSize * GroupId + 2;
    }

    public static class Group2
    {
        private const int GroupId = 2;

        public const int Step1 = FlowSteps.GroupSize * GroupId + 1;
        public const int Step2 = FlowSteps.GroupSize * GroupId + 2;
    }
}

如您所见,每组有100个步骤可用。如果这还不够,只需增加组大小即可。而你的currentStep现在只是一个int


0
投票

Patrick Hofman的回答是针对目标的。但是,如果你需要保留枚举,那么你可以通过使用静态的只读类来解决这个问题。这将允许您保留每个组可以包含的一组通用步骤。

enum Steps {
   Step1,
   Step2,
   Step3
};

static class Group1 {
     static readonly KeyValuePair<int, string> Step1 = 
         new KeyValuePair<int, string>(
             (int)Types.Group1_Value1, 
             Types.Group1_Value1.ToString());

     static readonly KeyValuePair<int, string> Step2 = 
         new KeyValuePair<int, string>(
                 (int)Types.Group1_Value1, 
                 Types.Group1_Value2.ToString());
 }    

 static class Group2 {
     public static readonly KeyValuePair<int, string> Step1 = 
         new KeyValuePair<int, string>(
             (int)Steps.Step1, 
             Steps.Step1.ToString());

     public static readonly KeyValuePair<int, string> Step2 = 
         new KeyValuePair<int, string>(
             (int)Steps.Step2, 
             "Step Two's Other Sneaky Name");

     public static readonly KeyValuePair<int, string> Step3 = 
         new KeyValuePair<int, string>(
             (int)Steps.Step3, 
             Steps.Step3.ToString());
 }

然后可以根据它们的值进行比较,并且可以替换步骤的替代名称 - 如上面的Group2.Step2。

Group1.Step1.Value == Group2.Step1.Value

更进一步,如果需要枚举或序列化,可以将每个组放在List<NameValuePair<int, string>>的集合中。

© www.soinside.com 2019 - 2024. All rights reserved.