我有以下枚举类型:
/// <summary>
/// TTE Node types.
/// </summary>
public enum E_TTE_NODES
{
/// <summary>
/// Represents FCM 0
/// </summary>
E_FCM0 = 0,
/// <summary>
/// Represents FCM 1
/// </summary>
E_FCM1,
/// <summary>
/// Represents FCM 2
/// </summary>
E_FCM2,
/// <summary>
/// Represents DCM 0
/// </summary>
E_DCM0,
/// <summary>
/// Represents DCM 1
/// </summary>
E_DCM1,
/// <summary>
/// Represents DCM 2
/// </summary>
E_DCM2,
/// <summary>
/// Represents CCM 0
/// </summary>
E_CCM0,
/// <summary>
/// Represents CCM 1
/// </summary>
E_CCM1,
/// <summary>
/// Represents CCM 2
/// </summary>
E_CCM2,
/// <summary>
/// Represents PDU C1
/// </summary>
E_PDU_C1,
/// <summary>
/// Represents the last node.
/// Must remain last.
/// </summary>
E_LAST,
}
我想初始化一个这样的通用列表:
// Should initialize to a capacity of 10
private List<Int32> transmitIndex = new List<Int32>((Int32)E_TTE_NODES.E_LAST);
是的,我知道我可以将数字10作为参数传递。枚举可能会在将来添加更多节点,但E_LAST
将始终是最后一个节点。我的问题是编译器说我无法将我的枚举转换为上面一行代码中的int。枚举值的默认值不是整数吗?
答案 0 :(得分:4)
您可以将int枚举类型转换为int,问题可能在其他地方。
这会产生你说的编译错误:
private List<Int32> transmitIndex = new List<Int32>(E_TTE_NODES.E_LAST);
这不会:
private List<Int32> transmitIndex = new List<Int32>((Int32)E_TTE_NODES.E_LAST);
答案 1 :(得分:1)
那应该没问题。例如,这没有问题编译:
using System;
using System.Collections.Generic;
enum Foo
{
Bar = 0,
Baz
}
public class Test
{
static void Main()
{
List<Int32> transmitIndex = new List<Int32>((Int32)Foo.Baz);
}
}
你能发布一个类似的简短但完整的程序,但无法编译吗?
您是否错过了using System;
?
答案 2 :(得分:1)
是的,您可以将枚举值转换为整数。如果E_LAST只是出于信息目的,你可以看看做这样的事情。
string numberOfElements = Enum.GetNames( typeof( E_TTE_NODES ) ).Length;
List<Int32> transmitIndex = new List<Int32>( numberOfElements );
答案 3 :(得分:0)
这确实有效。以下编译正常:
using System;
using System.Collections.Generic;
/// <summary>
/// TTE Node types.
/// </summary>
public enum E_TTE_NODES
{
/// <summary>
/// Represents FCM 0
/// </summary>
E_FCM0 = 0,
/// <summary>
/// Represents FCM 1
/// </summary>
E_FCM1,
/// <summary>
/// Represents FCM 2
/// </summary>
E_FCM2,
/// <summary>
/// Represents DCM 0
/// </summary>
E_DCM0,
/// <summary>
/// Represents DCM 1
/// </summary>
E_DCM1,
/// <summary>
/// Represents DCM 2
/// </summary>
E_DCM2,
/// <summary>
/// Represents CCM 0
/// </summary>
E_CCM0,
/// <summary>
/// Represents CCM 1
/// </summary>
E_CCM1,
/// <summary>
/// Represents CCM 2
/// </summary>
E_CCM2,
/// <summary>
/// Represents PDU C1
/// </summary>
E_PDU_C1,
/// <summary>
/// Represents the last node.
/// Must remain last.
/// </summary>
E_LAST,
}
public class Example
{
private List<Int32> transmitIndex = new List<Int32>((Int32) E_TTE_NODES.E_LAST);
public static void Main()
{
Example example = new Example();
Console.WriteLine(example.transmitIndex.Capacity);
Console.ReadKey();
}
}
这会在运行时按预期打印“10”。
话虽如此,我强烈建议您为所有枚举值分配值,而不仅仅是E_FCM0,如果你要这样做的话。
答案 4 :(得分:0)
如果您尝试获取此枚举中的项目总数,则可能需要尝试使用:
Enum.GetValues(typeof(E_TTE_NODES)).Length
另外,正如其他人指出的那样,为所有枚举值赋值可能是个好主意,这样如果在中间添加了某些内容,则与枚举值关联的整数值不会改变。如果将这些值写入数据库或文件,这可能会有所不同。