简体   繁体   中英

C# convert comma separated string to dynamic type

How do I convert a CSV string to an array of a type that is only known at run time. Say I have 2 array fields in my class of different types declared as int[] intArray and string[] strArray . I want a single function where I pass in 2 parameters the field name and CSV string. I can use the ...; FieldInfo f =... ; Type t = f.FieldType.GetElementType(); ...; FieldInfo f =... ; Type t = f.FieldType.GetElementType(); But what I can't do is declare List<t> because t is a variable and not a type. I saw one post suggesting csv.Split(',').Select(s => Convert.ChangeType(s, t)).ToArray() but this comes out as an object array not an int or string array; another post saying ...; var list = (IList) Activate.CreatInstance(...) ...; var list = (IList) Activate.CreatInstance(...) , which is fine that I can call list.Add(...) but then what do I do as I need an Array of t.

I'd recommend using a nuget package to do this parsing. CsvHelper has an example of how to deserialize to a given type .

I have bitten the bullet on this one and so will have to update my code if I need a new type like array of float numbers say is required but this suffices for what I need today, and I do agree with the other mentions about CSV what if my values had commas say addresses and came in as "\"12 George St, Sydney\",\"200 Sussex St, Sydney\"" then I would have to consider advanced CSV however again this is all I need for today.

class SetPropertyByName
{
    public object this[string fieldName]
    {
        set
        {
            FieldInfo field = this.GetType().GetField(fieldName, BindingFlags.Public | BindingFlags.Instance);
            if (null != field)
            {
                if (field.FieldType.IsArray && value is String)
                {
                    string newValue = (string)value;
                    if (string.IsNullOrEmpty(newValue))
                        value = null;
                    else
                    {
                        var conversionType = field.FieldType.GetElementType();
                        if (conversionType == typeof(string))
                        {
                            value = newValue.Split(',').ToArray();
                        }
                        else if (conversionType == typeof(int))
                        {
                            value = newValue.Split(',').Select(s => Convert.ToInt32(s)).ToArray();
                        }                         
                    }
                    field.SetValue(this, value);
                }
                else
                    field.SetValue(this, Convert.ChangeType(value, field.FieldType));
            }
        }
    }
}

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