方法,该方法接受多个枚举类型

本文关键字:方法 枚举 类型 | 更新日期: 2023-09-27 18:09:30

我有一个包含3种枚举类型的类

我想要一个方法,可以将所有3个枚举作为参数,并获得枚举的整数值。

public enum Enum1
{
    Fire = 0,
    Hour_24 = 1,
    Key_Switch = 2,
    Follower = 3,
    Entry_Delay1 = 4,
    Entry_Delay2 = 5,
    Intertior = 6,
    Local_Only = 7,
}
public enum Enum2
{
    Faulted = 0,
    Tampered = 1,
    Trouble = 2,
    Bypassed = 3,
    Inhibited = 4, 
    Low_Battery = 5,
    Loss_Supervision = 6,
    Reserved,
    Alarm_Memory = 8,
    Bypass_Memory = 9
}
private void BuildMessage ()
{
     List<Enum1> Enum1List = new List<Enum1>();
     FillBits(Enum1List);  // => Here I get an error.
}
// This method should accept Enum1 and Enum2
private Byte[] FillBits(List<Enum> EnumList)
{
     foreach (Enum e in EnumList)
     {
        int value = Convert.ToInt32(e);
     }
}

我怎样才能做到这一点?

感谢

方法,该方法接受多个枚举类型

只需使用泛型:

private Byte[] FillBits<T>(List<T> EnumList)
        where T : struct, IConvertible
{
    if (!typeof(T).IsEnum) 
    {
        throw new ArgumentException("T must be an enumerated type");
    }
    foreach (var e in EnumList)
    {
        int value = Convert.ToInt32(e);
    }
}

关于将泛型和枚举一起使用,请参阅此问题:

创建将T约束为枚举的泛型方法

既然枚举已经有一个int值,为什么不直接将其强制转换为int呢?

也许可以尝试使用对象?

private void BuildMessage()
{
    var enum1List = new List<object>();
    FillBits(enum1List);  // => Here I get an error.
}
// This method should accept Enum1 and Enum2
private Byte[] FillBits(IEnumerable<object> enumList)
{
    foreach (Enum e in enumList)
    {
        int value = Convert.ToInt32(e);
    }
}

这应该可以工作(没有检查或添加任何内容,只有基本功能(:

private void BuildMessage()
{
    List<Enum1> Enum1List = new List<Enum1>();
    Enum1List.Add(Enum1.Fire);
    Enum1List.Add(Enum1.Follower);
    FillBits(Enum1List);
}
private Byte[] FillBits<T>(List<T> enumList)
{
    foreach (var e in enumList)
    {
        int value = Convert.ToInt32(e);
    }
}
private Byte[] FillBits<T>(List<T> EnumList) where T: struct, IConvertable
{
     foreach (Enum e in EnumList)
     {
        int value = Convert.ToInt32(e);
     }
}

因为不能用枚举继承,所以无法真正确保函数只能在编译级别用List<Enum1>List<Enum2>List<Enum3>调用。你有两个真正的替代

1( 运行时类型检查

private Byte[] FillBits<T>(List<T> EnumList) Where T:struct, IConvertable
{
     if (typeof(T) != typeof(Enum1) && 
         typeof(T) != typeof(Enum2) && 
         typeof(T) != typeof(Enum3)) {
         throw new <EXCEPTION OF YOUR CHOICE!>;
     }
     foreach (Enum e in EnumList)
     {
        int value = Convert.ToInt32(e);
     }
}

或者将FillBits<T>移到基类中,这样就不能直接调用它并提供受保护的重载。

private Byte[] PrivateFillBits<T>(List<T> EnumList) where T: struct, IConvertable
{ ... }
protected Byte[] FillBits(List<Enum1> EnumList) {
   return this.PrivateFillBits(EnumList);
}
protected Byte[] FillBits(List<Enum2> EnumList) {
   return this.PrivateFillBits(EnumList);
}
protected Byte[] FillBits(List<Enum3> EnumList) {
   return this.PrivateFillBits(EnumList);
}