【发布时间】:2020-03-30 12:44:55
【问题描述】:
在一个类中,我有一些属性,两个静态字典(私有字段)一个静态方法。该方法初始化查询字典的属性,并在切换后返回一个字符串。由于某种原因,这些值始终返回为 null。下面是简化版:
using System;
using System.Collections.Generic;
namespace Test
{
class Program
{
public static string first { get; set; }
public static string second { get; set; }
public static string third { get; set; }
private static Dictionary<int, string> Symbols = new Dictionary<int, string>
{
[1] = "A",
[2] = "B",
[3] = "C"
};
private static Dictionary<int, string> Encoding = new Dictionary<int, string>
{
[1] = first,
[2] = second,
[3] = third
};
public static string Encode (int n)
{
string result;
first = Symbols[1];
second = Symbols[2];
third = Symbols[3];
switch (n)
{
case 1:
result = Encoding[1];
break;
case 2:
result = Encoding[2];
break;
case 3:
result = Encoding[3];
break;
default:
result = "EMPTY";
break;
}
return result;
}
static void Main(string[] args)
{
Console.WriteLine(Encode(1));
}
}
}
Encode(4) 例如正确返回字符串“EMPTY”,但从 1 到 3 返回 null。我错过了什么?有没有更正确/干净的方法来做同样的事情?谢谢!
【问题讨论】:
-
您正在调用
result = Encoding[1],Encoding类型的Encoding字段已使用数字索引器初始化,但它指向空值属性在初始化时我>。更改属性first的分配不会更改字典正在使用的值,这将保持null。 -
case 1: return first会为您保存字典和错误。开关其实和字典是一回事,只是不能在运行时修改。