I am writing a simple parser that takes a format string 20100101,1,2,fooand instantiates the following class:
public class Foo
{
public DateTime TheDate { get; set; }
public int TheFirstInt { get; set; }
public int TheSecondInt { get; set; }
public string TheString { get; set; }
}
I would like to be able to declare my parsers for each property as an array (for example) Func<>sto make the code more readable (in terms of correlating the elements in the string with the parsing code used).
Func<string, object>[] parsers = new Func<string, object>[]
{
s => DateTime.ParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture),
s => int.Parse(s),
s => int.Parse(s),
s => s
};
I would like for me to be able to iterate through parsers, properties FooClassand values in fooItemsin one loop:
Foo fooInstance = new Foo();
string[] fooItems = fooString.Split(',');
for (int i = 0; i < parsers.Length; i++)
{
fooInstance.Properties[i] = parsers[i](fooItems[i]);
// range-checking and error handling excluded from this example
}
However, this, of course, will not work, because:
- It does not address the issue of how to iterate over properties
fooInstance - He does not analyze scattered values
Anyone at least on how to write a "nice" parser like this?