Skip to main content
 首页 » 编程设计

c#之枚举类型的通用签名

2024年02月23日11lovecherry

我在我的项目中定义了几个 Enum 类型,用于对象特定的状态标识符:

  public enum ObjectAState 
  { 
    ObjectAAvailable, 
    ObjectADeleteRequested, 
    ObjectADeleted 
  } 
  public enum ObjectBState 
  { 
    ObjectBCreationRequested, 
    ObjectBCreationFailed, 
    ObjectBDeleteRequested, 
    ObjectBDeleted 
  } 

任何使用 ObjectA 的人都只能引用 ObjectA 枚举,所有其他对象也是如此——它们的枚举是隔离的,这使得它们更容易理解,因为不适用于对象的状态没有显示(这这就是为什么我不把所有对象的所有状态都放在一个 enum 中的原因)。

对于一个给定的状态,可以跟随有零个、一个或多个其他状态(在相同的 enum 中);根据定义,也有某些状态不能遵循。例如,在 ObjectA 中,状态可以从 ObjectAAvailable 转换到 ObjectADeleteRequested,从 ObjectADeleteRequested 转换到 ObjectADeleted,但不是直接从 ObjectAAvailable 到 ObjectADeleted。在每个对象中都有一段乏味且重复的代码来强制执行有效的状态转换,我想用一个方法替换它。

作为测试,我这样做了:

Dictionary<ObjectAState, List<ObjectAState>> Changes = new Dictionary<ObjectAState, List<ObjectAState>>(); 

这是一个通过 ObjectAState 作为键访问的 Dictionary,包含其他 ObjectAState 值的 List指示因此填充的有效转换:

Changes.Add(ObjectAState.ObjectAAvailable, new List<ObjectAState> { ObjectAState.ObjectADeleteRequested }); 
Changes.Add(ObjectAState.ObjectAADeleteRequested, new List<ObjectAState> { ObjectAState.ObjectADeleted }); 
Changes.Add(ObjectAState.ObjectADeleted, null); 

我有一个看起来像这样的方法:

public bool StateTransitionIsValid(ObjectAState currentState, ObjectAState targetState) 
{ 
  return Changes[currentState].Contains(targetState); 
} 

这非常有效 - ObjectA 的用户只需传入对象当前和目标状态的 enum 并得到一个简单的 true 或 false 来判断转换是否有效。那么,如何使这个通用化以便相同的方法可以处理来自其他对象的枚举?

我试过这个:

Dictionary<Enum, List<Enum>> Changes = new Dictionary<Enum, List<Enum>>(); 

它编译没有错误 - 但是向字典添加条目的代码失败了:

Changes.Add(ObjectAState.ObjectAAvailable, new List<ObjectAState> { ObjectAState.ObjectADeleteRequested }); 
 
Error   1   The best overloaded method match for 'System.Collections.Generic.Dictionary<System.Enum,System.Collections.Generic.List<System.Enum>>.Add(System.Enum, System.Collections.Generic.List<System.Enum>)' has some invalid arguments 
Error   2   Argument 2: cannot convert from 'System.Collections.Generic.List<MyApp.ObjectAState>' to 'System.Collections.Generic.List<System.Enum>' 

我四处寻找,似乎看不出我做错了什么。有人知道为什么我的“通用”版本无法编译吗?

请您参考如下方法:

您的方法或类必须是泛型定义的,这样您才能使用实际的泛型类型。

困难在于没有办法在编译时完全强制泛型类型是枚举。这可能是您最接近的:

public class MyTestClass<T> 
    where T : struct, IConvertible // Try to get as much of a static check as we can. 
{ 
    // The .NET framework doesn't provide a compile-checked 
    // way to ensure that a type is an enum, so we have to check when the type 
    // is statically invoked. 
    static EnumUtil() 
    { 
        // Throw Exception on static initialization if the given type isn't an enum. 
        if(!typeof (T).IsEnum)  
            throw new Exception(typeof(T).FullName + " is not an enum type."); 
    } 
 
    Dictionary<T, List<T>> Changes = new Dictionary<T, List<T>>(); 
    ... 
}