Trying to write a nice parser

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).

// Production code would contain parsers with error checking etc.
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?

+3
3

Action Func :

Action<string, FooClass>[] actions = new Action<string, FooClass>[] {
    (s, c) => c.TheDate = DateTime.ParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture),
    (s, c) => c.TheFirstInt = Int32.Parse(s)
    // ...
}

for (int i = 0; i < fooItems.Length; ++i)
    actions[i](fooItems[i], fooInstance);
+2

, , , "" , : http://www.codeplex.com/irony

(, CSV), http://www.filehelpers.com/

:

[DelimitedRecord(",")]
public class Foo
{
    [FieldConverter(ConverterKind.Date, "yyyyMMdd")]
    public DateTime TheDate { get; set; }
    public int TheFirstInt { get; set; }
    public int TheSecondInt { get; set; }
    public string TheString { get; set; }
}

:

FileHelperEngine engine = new FileHelperEngine(typeof(Foo));
Foo[] fs = engine.ReadFile("FileIn.txt") as Foo[];
+2

: :

fooInstance.GetType().GetProperty("SomeProp").SetValue(fooInstance, "SomeProp", val);
0

Source: https://habr.com/ru/post/1730879/


All Articles