[英]What is the best way to compare two different enums?
我在想比较两个不同枚举值的最佳方法是什么。
例:
public enum ExampleEnumA
{
ExampleValue
}
public enum ExampleEnumB
{
ExampleValue
}
if (ExampleEnumA.ExampleValue.ToString() == ExampleEnumB.ExampleValue.ToString())
{
}
比较字符串是可行的,但是我知道这不是最有效,最轻松的方法。 如何才能做得更好?
编辑:
也许这是一个设计缺陷,但这是一个真实项目的问题,而不是我对枚举的错误理解。 这就是它的样子,没有时间重构整个方法。
public interface IProvider
{
Enum SectionType { get; }
}
public class FirstProvider : IProvider
{
public Enum SectionType
{
get { return ExampleEnumA.ExampleValue; }
}
}
public class SecondProvider : IProvider
{
public Enum SectionType
{
get { return ExampleEnumB.ExampleValue; }
}
}
public class Program
{
public void TmpMethod(Enum sectionType)
{
var provider = GetFromIoC...
if (provider.SectionType == sectionType)
{
//...
}
}
}
枚举就像是常规类基于整数的常量之上的抽象层。
即使两个枚举值是相同的整数但属于不同的枚举类型,该抽象也包括对false
评估。
比较具有相同基础值的两种不同枚举类型的最佳方法是什么? 我会回答, 如果您需要执行此评估 , 那应该是设计缺陷 。
例如,假设我们实现了以下枚举:
public enum States
{
Open = 1,
Closed
}
public enum SpecialFolders
{
ProgramFiles86 = 1,
ProgramFiles64
}
像States.Open == SpecialFolders.ProgramFiles86
这样的东西States.Open == SpecialFolders.ProgramFiles86
吗? 潜在地,它们似乎是相等的(它们不会),因为两个枚举值的基础值均为1
,但是如果枚举类型不同,则1
并不意味着相同。
就像说...
...是相同的:
...您可以打败将常量键入为int
枚举的目的:
if ((int)ExampleEnumA.ExampleValue == (int)ExampleEnumB.ExampleValue)
{
}
...如果基础类型为int
。 也可能long
:
public enum SomeEnum : long
{
}
...并且您需要将评估的左右部分转换为long
,依此类推。
无论如何,我坚持你不应该这样。 也许您应该改用常规的常量类,并且避免每次求值两次强制转换:
public static class States
{
public const int Open = 1;
public const int Closed = 2;
}
public static class Materials
{
public const int Steel = 1;
public const int Wood = 1;
}
// true! but not that true... I can't understand why these constants equal...
if(States.Open == Materials.Wood)
{
}
顺便说一句,我仍然认为这是一个设计缺陷 ,您应该避免不使用枚举来解决错误的设计决策。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.