I have a given type
and a Comma Separated Values string
:
Type type = service.getType();
String csv = "1,2,3";
I need to convert the csv
string to an IEnumerable
of type
.
I know that type
will be numeric, eg, int
, short
, long
, etc.
I am able to spit the csv
and convert each one to given type
..
String[] inputs = csv.Split(',');
TypeConverter converter = TypeDescriptor.GetConverter(modelType);
if (converter != null) {
foreach (String input in inputs) {
if (converter.CanConvertTo(type)) {
var number = converter.ConvertFromString(input);
// Add number to an IEnumerable of numbers
}
}
}
I am not able to create an IEnumerable
of type
and add numbers to it.
How can I do this?
You actually have the type at run-time, so you will need to use reflection to create an object of type List<T>
where T is the instance of class Type
which you are getting from service. The following code will create an instance of type List<T>
while T
is not type at compile time but instead it is resolved at run-time. Following is the code to create that:
var listTypeInstance = typeof(List<>);
var instanceList = listTypeInstance.MakeGenericType(type);
var numbers = (IList)Activator.CreateInstance(instanceList);
Now you can call the Add
method and add each number in it like:
var number = converter.ConvertFromString(input);
numbers.Add(number);
Adjusted in your code will look something like following:
var listTypeInstance = typeof(List<>);
var instanceList = listTypeInstance.MakeGenericType(type);
var numbers = (IList)Activator.CreateInstance(instanceList);
foreach (String input in inputs) {
if (converter.CanConvertTo(type)) {
var number = converter.ConvertFromString(input);
// Add number to an IEnumerable of numbers
numbers.Add(number);
}
Use dynamic
to skip the compile-time error.
var runtimeTypes = new List<Type>
{
typeof(int),
typeof(long)
};
foreach (var item in runtimeTypes)
{
var listType = typeof(List<>).MakeGenericType(item);
dynamic list = Activator.CreateInstance(listType);
list.Add(1); // Call Add() on dynamic works!
Console.WriteLine(list[0]);
}
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.