处理独特IF的优雅方式

时间:2016-08-10 15:02:28

标签: c# winforms

打开不同的建议。我的问题如下:我有一个中等大小的文本文件(~100行),需要从这个配置文件中的特定行提取信息

AcquisitionMode=3           --> 3
MovingCalculationLoop=1
MovingCalculationType=0
ReadoutMode=4               --> 4
ReadoutRegisterMode=0

例如,在这些行中,我需要知道AcquisitionMode为3,将其写入另一个int AcqMode。 有没有比写15条if语句更优雅的方式? 我现在的是:

if (line.Contains("FrameTransferAcquisitionMode")) { LabelTemp2.Text = Regex.Match(line, @"\d+$").Value.ToString(); }
else if (line.Contains("AcquisitionMode")) { LabelTemp1.Text = Regex.Match(line, @"\d+$").Value.ToString(); }

忽略labeltemps,这些仅用于测试目的 感谢

2 个答案:

答案 0 :(得分:3)

您可以在不同的预期模式和标签之间创建地图:

Dictionary<string,Label> modeMap = new Dictionary<string,Label>()
{
    { "FrameTransferAcquisitionMode", LabelTemp2 },
    { "AcquisitionMode", LabelTemp1 },
};

然后从行中提取模式并在字典中执行查找:

string mode = line.Split('=')[0];
Label label;
if(modeMap.TryGetValue(mode, out label))
{
    label.Text = Regex.Match(line, @"\d+$").Value.ToString();
}

答案 1 :(得分:0)

var lines = File.ReadLines("settings.ini");
var lookup = lines.ToLookup(l => l.Split('=')[0], l => l.Split('=').ElementAtOrDefault(1));

string sAcquisitionMode = lookup["AcquisitionMode"].FirstOrDefault(); // null if not found
int AcqMode;
int.TryParse(sAcquisitionMode, out AcqMode); // AcqMode is set to 0 if the sting can't be parsed

<强>更新

尝试将文件解析为XML

的替代方法
var text = File.ReadAllText("settings.ini").Trim().Replace("\r\n", "' ").Replace("=", "='"); // Example: "a=1" to "a='1'"
//text = text.Replace("[", "").Replace("]", "='"); // optional if your file has any [sections]  Example: "[a]" to "a=''"
var x = XElement.Parse("<x " + text + "' />");
int AcqMode = (int)x.Attribute("AcquisitionMode"); // in VB.NET this will be Dim AcqMode = Cint(x.@AcquisitionMode)