我有一个实例化和填充Dictionary的函数。我使用该函数将Byte键(其参数)转换为枚举值(其返回值)。
/// <summary>
/// Convert the first byte of the received data from USB into a Model B event
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
Model_B_Event Get_Event_From_Data(Byte[] data)
{
Dictionary<Byte, Model_B_Event> map = new Dictionary<byte, Model_B_Event>();
Model_B_Event matching_event = Model_B_Event.NO_EVENT;
map.Add(0, Model_B_Event.SEND_MODEL_ID);
map.Add(5, Model_B_Event.SEND_RELAY_VOLTAGE);
map.Add(6, Model_B_Event.SEND_SPARE_STATUS);
map.TryGetValue(data[0], out matching_event);
return matching_event;
}
我在用C ++术语思考,我想将静态属性添加到
static Dictionary<Byte, Model_B_Event> map = new Dictionary<byte, Model_B_Event>();
这样字典只在每次运行函数时构建一次。如果我之前已经构建了字典,我只会检查一个布尔标志。
但是,静态属性在C#中不可用于局部变量。
有没有办法只构建一次这个字典,并且只能在函数本地使用它?我不想在课堂上分享它。
感谢。
答案 0 :(得分:3)
据我所知,除了作为类变量之外,没有办法在C#中声明静态变量。但是,通过将您的字段声明为私有字段,不存在外部意外消费的风险;它只能从类本身内访问。
您可以将其声明为静态延迟初始化字段:
private static readonly Lazy<Dictionary<byte, Model_B_Event>> map =
new Lazy<Dictionary<byte, Model_B_Event>>(() =>
new Dictionary<byte, Model_B_Event>
{
{ 0, Model_B_Event.SEND_MODEL_ID },
{ 5, Model_B_Event.SEND_RELAY_VOLTAGE },
{ 6, Model_B_Event.SEND_SPARE_STATUS },
});
/// <summary>
/// Convert the first byte of the received data from USB into a Model B event
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
Model_B_Event Get_Event_From_Data(Byte[] data)
{
if (map.Value.TryGetValue(data[0], out matching_event))
return matching_event;
return Model_B_Event.NO_EVENT;
}