【发布时间】:2012-03-14 08:12:54
【问题描述】:
我想创建一个解析器,将字符串标记转换为基于键的类型化对象。
我的第一次尝试,借鉴Dictionary<T,Delegate> with Delegates of different types: Cleaner, non string method names?的想法
delegate T Parser<T>(string item);
public class TableParser
{
static IDictionary<string, Pair<PropertyInfo, Delegate>> _PARSERS;
static Type DOMAIN_TYPE;
static TableParser()
{
DOMAIN_TYPE= typeof(Domain);
Dictionary<string, Pair<PropertyInfo, Delegate>> parsers = new
Dictionary<string, Pair<PropertyInfo, Delegate>>()
{
{ "PropertyOne", new Pair<PropertyInfo,Delegate>(
DOMAIN_TYPE.GetProperty("PropertyOne"),
(Parser<double>) double.Parse ) },
};
_PARSERS = parsers;
}
public List<Domain> Parse(string filename)
{
List<Domain> domains = new List<Domain>();
List<List<string>> data =
CVSParser.Instance.Parse(filename);
List<string> headers = data[0];
for (int i = 1; i < data.Count; i++)
{
List<string> row = data[i];
}
return domains;
}
private Dictionary<int, Pair<PropertyInfo, Delegate>> FindParsers(List<string> headers)
{
Dictionary<int, Pair<PropertyInfo, Delegate>> parsers =
new Dictionary<int, Pair<PropertyInfo, Delegate>>();
int i = 0;
headers.ForEach(h =>
{
if (_PARSERS.ContainsKey(h))
{
parsers[i] = _PARSERS[h];
}
++i;
});
return parsers;
}
private Domain Create(List<string> data,
Dictionary<int, Pair<PropertyInfo, Delegate>> parsers)
{
Domain domain = new Domain();
foreach (KeyValuePair<int, Pair<PropertyInfo, Delegate>> parser in parsers)
{
string datum = data[parser.Key];
parser.Value.First.SetValue(domain,
/* got stuck here */ parser.Value.Second,
null);
}
return domain;
}
}
当我需要使用解析器时,我陷入了重新发现解析器类型的困境。我需要根据PropertyInfo 将其转换回Parser<double>、Parser<int> 等。
标准 CSV 解析器在这种情况下不起作用,因为域的属性来自多个文件。
【问题讨论】: