我必须实现类似这样的解决方案 - 我的 C# 函数我使用了很多硬编码的五位数代码。我想要的是将这些硬编码值移动到一个映射配置文件(一些 xml)中,该配置会将代码映射到可在我的函数中使用的常量。
这将有助于在不重新编译源代码的情况下更新代码值。
XML 就像:
<Codes>
<Code>
<key>code_name_1</key>
<value>value_1</value>
</Code>
...
</Codes>
或
<Codes>
<Code key='code_name_1' value='value_1'>
<Code key='code_name_2' value='value_2'>
<Code key='code_name_3' value='value_3'>
...
</Codes>
映射类是:
static class codeMapping
{
const sting code1 = "code_name_1";
const sting code2 = "code_name_2";
const sting code3 = "code_name_3";
const sting code4 = "code_name_4";
...
}
我想获取这些值的函数:
class someClass
{
...someFunction(string someCode)
{
...
if(someCode == codeMapping.code1)
...do something
var temp2 = codeMapping.code2;
...
}
}
如何将codeMapping类的常量变量初始化为对应的配置值?任何更好的设计理念也被接受。
最佳答案
改为使用静态只读字段并在构造函数中对其进行初始化。希望这就是您要实现的目标。
class Program
{
static void Main(string[] args)
{
var s = CodeMapping.Code1;
}
public static class CodeMapping
{
private static readonly string _code1;
private static readonly string _code2;
static CodeMapping()
{
string filePath = "code file path";
var doc = XElement.Load(filePath);
_code1 = doc.Elements().SingleOrDefault(r => r.Element("key").Value == "code_name_1").Element("value").Value;
_code2 = doc.Elements().SingleOrDefault(r => r.Element("key").Value == "code_name_2").Element("value").Value;
}
public static string Code1 { get { return _code1; }}
public static string Code2 { get { return _code2; } }
}
}
关于c# - 可以从 xml 返回成员值的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25203212/