[英]Compare Enum with Class, best practice?
在我的程序中,我有一個按“組”划分的枚舉,例如(為清楚起見而重命名):
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
}
}
更清楚了,但是現在我無法通過執行以下操作來比較我的currentStep:
FlowSteps currentStep = ...;
if (currentStep == FlowSteps.GROUP1.Step1) { //Do something }
關於如何保持我的Enum的這種分組以及在不增加太多復雜性的情況下能夠比較類的任何建議?
您將如何進行?
我認為列舉枚舉不是正確的方法。 我將使用一組帶有整數的類,使它們產生唯一的數字。
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
。
帕特里克·霍夫曼(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>>
的集合中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.