I want to create a parser that convert string tokens to typed objects based on a key.
My first stab, borrowing ideas from 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;
}
}
I got stuck at re-discovering the type of the parser when I need to use it. I need to cast it back to Parser<double>
, Parser<int>
, etc depending on PropertyInfo
.
A canned CSV parser doesn't work in this case because Domain's properties come from multiple files.