How to cast to a dynamic class?

Deadly 提交于 2019-12-12 03:08:40

问题


I am trying use filehelpersclass builder but I am kinda confused on what to do with it.

       var cb = new DelimitedClassBuilder("temp", ",") { IgnoreFirstLines = 0, IgnoreEmptyLines = true, Delimiter = ","  };
        var sr = new StreamReader(stream);
        var headerArray = sr.ReadLine().Split(',');
        foreach (var header in headerArray)
        {
            var fieldName = header.Replace("\"", "").Replace(" ", "");
            cb.AddField(fieldName, typeof(string));
        }

        var engine = new FileHelperEngine(cb.CreateRecordClass());
        var result = engine.ReadStream(sr);

The DelimitedClassBuilder takes in as it's first parameter a "className' and then "delimiter"

    //
    // Summary:
    //     Creates a new DelimitedClassBuilder.
    //
    // Parameters:
    //   className:
    //     The valid class name.
    //
    //   delimiter:
    //     The delimiter for that class.
    public DelimitedClassBuilder(string className, string delimiter);

I then go through the first row of the stream what contains the header what I will later on use as the fieldNames for this "class".

The last line reads all the rest of the information and returns it as an object array[]. I see inside it they are of class "temp".

Yet I don't know how actually cast it to the class "temp". Right now I don't really know how to get at the data. I know I can't just do something like

result[0].SomeFieldName as the fieldName could change from run to run. So this also makes me wonder why it makes a class in the first place if I going to have to do something like get it by index or something.

As you can see right now I am very confused.


回答1:


The easiest way is demonstrated in the examples.

You use

DataTable dt = engine.ReadStreamAsDT(sr);

and then access the results with something like:

foreach (DataRow row in dt.Rows) // Loop over the rows.
{
    Console.WriteLine("--- Row ---"); // Print separator.
    foreach (var item in row.ItemArray) // Loop over the columns.
    {
        Console.Write("Item: "); // Print label.
        Console.WriteLine(item); 
        /// the Type of item will be whatever you defined when you
        /// called ClassBuilder.AddField() (String in your example)
    }
}
Console.ReadLine();


来源:https://stackoverflow.com/questions/9203548/how-to-cast-to-a-dynamic-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!