可能重复:
C# 中的两个枚举何时相等?
我有以下类作为简单状态机的一部分。
请注意,所有泛型类型参数都必须是枚举。这已在构造函数中强制执行(此处未显示)。
// Both [TState] and [TCommand] will ALWAYS be enumerations.
public class Transitions<TState, TCommand>: List<Transition<TState, TCommand>>
{
public new void Add (Transition<TState, TCommand> item)
{
if (this.Contains(item))
throw (new InvalidOperationException("This transition already exists."));
else
this.Add(item);
}
}
// Both [TState] and [TCommand] will ALWAYS be enumerations.
public class Transition<TState, TCommand>
{
TState From = default(TState);
TState To = default(TState);
TCommand Command = default(TCommand);
}
public sealed class TransitionComparer<TState>:
IComparer<TState>
{
public int Compare (TState x, TState y)
{
int result = 0;
// How to compare here since TState is not strongly typed and is an enum?
// Using ToString seems silly here.
result |= x.From.ToString().CompareTo(y.From.ToString());
result |= x.To.ToString().CompareTo(y.To.ToString());
result |= x.Command.ToString().CompareTo(y.Command.ToString());
return (result);
}
}
以上确实可以编译,但我不确定这是否是处理作为泛型类型参数传入的枚举的正确方法。
注意:比较功能不需要记住排序。相反,它需要检查确切的重复项。