[英]Static Dictionary fields used to implement static method
在一个类中,我有一些属性,两个静态字典(私有字段)一个静态方法。 该方法初始化查询字典的属性,并在切换后返回一个字符串。 由于某种原因,这些值总是返回为 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 返回空值。 我错过了什么? 有没有更正确/干净的方法来做同样的事情? 谢谢!
该方法初始化查询字典的属性,并在切换后返回一个字符串。
是的,当方法被调用时,属性将被初始化。 但是在Encoding
字典填充后发生。 Encoding
字典会在类型初始化后立即填充,此时所有属性的值都将为 null。
我完全不清楚你在这里试图实现什么,但我强烈建议重新设计代码以避免这种混淆。
(我通常也会警告不要使用静态可变属性,我至少建议为它们使用常规的 .NET 命名约定。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.