我有一个包含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);
}
}
我怎样才能做到这一点?
由于
答案 0 :(得分:6)
只需使用通用:
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);
}
}
请参阅此问题,将generic和Enum一起使用:
答案 1 :(得分:2)
由于枚举已经有一个int值,为什么不把它强制转换为int?
答案 2 :(得分:2)
尝试使用对象吗?
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);
}
}
答案 3 :(得分:2)
这应该有用(没有检查或任何添加,只是基本功能):
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);
}
}
答案 4 :(得分:2)
private Byte[] FillBits<T>(List<T> EnumList) where T: struct, IConvertable
{
foreach (Enum e in EnumList)
{
int value = Convert.ToInt32(e);
}
}
因为您无法使用Enums继承,所以您无法确保只能在编译级别使用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);
}