下面,我编写了一个简单的配置管理器,它直接将配置元素从文件加载到字典中,并且还具有一个函数,用于通过字典中的键获取元素。我只是想知道我是否能做些什么来改善这一点。
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Apple_Server.Application.Base.Core.Config
{
class ConfigManager
{
private readonly Dictionary<string, string> configValues = null;
private readonly FileInfo configFile = null;
private readonly ILog _log = null;
private bool _initialized = false;
public ConfigManager(string filePath)
{
this.configValues = new Dictionary<string, string>();
this.configFile = new FileInfo(filePath);
this._log = LogManager.GetLogger(typeof(ConfigManager));
}
public void Initialize()
{
if (!this._initialized)
{
try
{
foreach (string line in File.ReadLines(this.configFile.ToString()).Where(s => !string.IsNullOrWhiteSpace(s) && !s.StartsWith("#") && s.Contains("=")))
{
this.configValues[line.Split('=')[0]] = line.Split('=')[1];
}
}
catch (FileNotFoundException)
{
this._log.Error("Unable to find the config file.\nPress any key to exit.");
Console.ReadKey(true);
Environment.Exit(Environment.ExitCode);
}
catch (Exception)
{
Console.WriteLine("opppppps");
}
}
this._initialized = true;
}
public string GetConfigElement(string Key)
{
return configValues[Key];
}
}
}发布于 2015-10-27 19:20:36
还有一件事,玛特的穆格没有提到,但它困扰着我。是这个循环:
foreach (string line in File.ReadLines(this.configFile.ToString()).Where(s => !string.IsNullOrWhiteSpace(s) && !s.StartsWith("#") && s.Contains("=")))
{
this.configValues[line.Split('=')[0]] = line.Split('=')[1];
}枚举也太长了。您应该打破它并使用helper变量来使它更易读和更易于维护:
var lines =
File.ReadLines(configFile.ToString())
.Where(s =>
!string.IsNullOrWhiteSpace(s)
&& !s.StartsWith("#")
&& s.Contains("=")))
foreach (string line in lines)
{
configValues[line.Split('=')[0]] = line.Split('=')[1];
}@Mat的Mug建议将行检查逻辑移到单独的方法中。你有两个选择:要么是普通的要么是匿名的。然后就会变成这样:
var isConfigLine = new Func<string, bool>(line =>
!string.IsNullOrWhiteSpace(s)
&& !s.StartsWith("#")
&& s.Contains("="));
var lines =
File.ReadLines(configFile.ToString())
.Where(isConfigLine)Where部件现在又短又干净,您可以轻松地调整行条件。但是,如果你想测试它,那么一个正常的方法会更好。
但是,这个索引/键:
line.Split('=')[0]太疯狂了:-)
在这里,您还应该在这里使用一个助手变量:
var splittedLine = line.Split('=');
const int keyIndex = 0;
const int valueIndex = 1;
configValues[splittedLine[keyIndex]] = splittedLine[valueIndex];现在,您甚至不必考虑什么是什么,因为变量名称已经解释了一切。
https://codereview.stackexchange.com/questions/108918
复制相似问题