简体   繁体   中英

Instantiate object depending on type

I have a function that reads a CSV file and returns a list of objects whose parameters depends on the content of the CSV. Right now it works if I hardcode one object. I would like to return different object types.

    public static List<CSVObject> ImportCsvIntoObject(string csvFile, string delimiter)
    {
        List<CSVObject> list = new List<CSVObject>();

        using (TextFieldParser csvReader = new TextFieldParser(csvFile))
        {
            csvReader.SetDelimiters(new String[] { delimiter });
            csvReader.HasFieldsEnclosedInQuotes = true;

            //Parse the file and creates a list of CSVObject
            //example with a csv file with 3 columns
            while (!csvReader.EndOfData)
            {
                string[] fieldData = csvReader.ReadFields();
                string parameter1 = fieldData[0];
                string parameter2 = fieldData[1];
                string parameter3 = fieldData[2];

                CSVObject example = new CSVObject(parameter1, parameter2, parameter3);
                list.Add(example);
            }
        }
        return list;
    }

The following solution works but I'm not sure if there are not better ways to do this.

    public static List<Object> ImportCsvIntoList(string csvFile, string delimiter, Type type)
    {
        List<Object> list = new List<Object>();

        using (TextFieldParser csvReader = new TextFieldParser(csvFile))
        {
            csvReader.SetDelimiters(new String[] { delimiter });
            csvReader.HasFieldsEnclosedInQuotes = true;

            while (!csvReader.EndOfData)
            {

                string[] fieldData = csvReader.ReadFields();
                string parameter1 = fieldData[0];
                string parameter2 = fieldData[1];
                string parameter3 = fieldData[2];

                var example = Activator.CreateInstance(type, parameter1, parameter2, parameter3);
                list.Add(example);
            }
        }
        return list;
    }

Furthermore, right now it only works with a hardcoded amount of parameters. Unfortunately, my objects all have a different amount of parameters. How can I call Activator.CreateInstance with different amount of parameters ?

It is my first question so sorry if it isn't written properly, suggestion to improve are more than welcome.

The Activator.CreateInstance() function can take an array of parameters , so that you might not know how many you need before runtime, but as you read your CSV, you create arrays corresponding to the number of parameters needed for this particular object (fortunately, your field data object seems to already do this).

So it could be like this :

string[] fieldData = csvReader.ReadFields();

var example = Activator.CreateInstance(type, fieldData);
list.Add(example);

This is because the Activator.CreateInstance function uses the params keyword

The following might work for you using generics and delegates

public static List<T> ImportCsvIntoObject<T>(string csvFile, string delimiter, Func<List<string>, T> createObject)
    {
        List<T> list = new List<T>();

        using (TextFieldParser csvReader = new TextFieldParser(csvFile))
        {
            csvReader.SetDelimiters(new String[] { delimiter });
            csvReader.HasFieldsEnclosedInQuotes = true;

            //Parse the file and creates a list of CSVObject
            //example with a csv file with 3 columns
            while (!csvReader.EndOfData)
            {
                string[] fieldData = csvReader.ReadFields();

                CSVObject example = createObject(fieldData.ToList())
                list.Add(example);
            }
        }
        return list;
    }

And you would call the following using:

List<CSVObject> objectList = ImportCsvIntoObject("csvData", ",", (list) => { new CSVObject(list[0], list[1], list[2]); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM