我需要将配置文件的多个部分转换为字典。这些字典的价值有不同的类型。以下两类工作,但他们几乎是相同的:如何从配置文件重构高度重复的阅读部分
public class IntConfigSection
{
private static readonly ILog Log = LogManager.GetLogger(typeof(IntConfigSection));
public static Dictionary<String, int> LoadSection(string sectionName)
{
var ret = new Dictionary<String, int>();
try
{
var offsetsHash = (Hashtable)ConfigurationManager.GetSection(sectionName);
foreach (DictionaryEntry entry in offsetsHash)
{
ret.Add((String)entry.Key, int.Parse((String)entry.Value));
}
}
catch(Exception e)
{
Log.ErrorFormat("LoadSection:" + e);
}
return ret;
}
}
public class StringConfigSection
{
private static readonly ILog Log = LogManager.GetLogger(typeof(StringConfigSection));
public static Dictionary<String, String> LoadSection(string sectionName)
{
var ret = new Dictionary<String, String>();
try
{
var offsetsHash = (Hashtable)ConfigurationManager.GetSection(sectionName);
foreach (DictionaryEntry entry in offsetsHash)
{
ret.Add((String)entry.Key, (String)entry.Value);
}
}
catch (Exception e)
{
Log.ErrorFormat("LoadSection:" + e);
}
return ret;
}
}
要求下面的代码不能正常工作,但它证明了什么,我试图完成:
public class ConfigSection<T>
{
private static readonly ILog Log = LogManager.GetLogger(typeof(StringConfigSection));
public static Dictionary<String, T> LoadSection(string sectionName)
{
var ret = new Dictionary<String, T>();
try
{
var offsetsHash = (Hashtable)ConfigurationManager.GetSection(sectionName);
foreach (DictionaryEntry entry in offsetsHash)
{
//builds but does not always do what I want
ret.Add((String)entry.Key, (T)entry.Value);
// does not compile
//ret.Add((String)entry.Key, T.Parse((String)entry.Value));
}
}
catch (Exception e)
{
Log.ErrorFormat("LoadSection:" + e);
}
return ret;
}
}
编辑:我的最终版本看起来如下:
public class ConfigSectionLoader
{
public static Dictionary<String, int> LoadIntSection(string sectionName)
{
return ConfigSection<int>.LoadSection(sectionName, int.Parse);
}
public static Dictionary<String, String> LoadStringSection(string sectionName)
{
return ConfigSection<String>.LoadSection(sectionName, val => val);
}
}
internal class ConfigSection<T>
{
private static readonly ILog Log = LogManager.GetLogger(typeof(StringConfigSection));
internal static Dictionary<String, T> LoadSection(string sectionName, Func<String, T> parseFunc)
{
var ret = new Dictionary<String, T>();
try
{
var hash = (Hashtable)ConfigurationManager.GetSection(sectionName);
foreach (DictionaryEntry entry in hash)
{
ret.Add((String)entry.Key, parseFunc((String)entry.Value));
}
}
catch (Exception e)
{
Log.ErrorFormat("LoadSection:" + e);
}
return ret;
}
}
我唯一关心的是:val => val最简单的lambda什么也不做?
哦;抱歉,阿恩,我没有注意到你已经更新了你的主要问题,我在下面误解了你的问题。我想我会以不同的方式说出来。但如果我理解你的问题,那么我会说是,val => val是做这种类型的“传递”的方式,在那里你需要lambda的结果与参数相同。:) – shelleybutterfly