简体   繁体   English

创建IEnumerable <T> 并添加项目

[英]Create IEnumerable<T> and add items to it

I have a given type and a Comma Separated Values string : 我有一个给定的type和一个逗号分隔值string

Type type = service.getType();

String csv = "1,2,3";

I need to convert the csv string to an IEnumerable of type . 我需要将csv字符串转换为IEnumerable type

I know that type will be numeric, eg, int , short , long , etc. 我知道type将是数字,例如intshortlong等等。

I am able to spit the csv and convert each one to given type .. 我能够吐出csv并将每个转换为给定的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. 我无法创建typeIEnumerable并向其添加数字。

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. 实际上,您在运行时就拥有该类型,因此您将需要使用反射来创建类型为List<T>的对象,其中T是从服务中获取的Type类的实例。 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. 以下代码将创建List<T>类型的实例,而T在编译时不是类型,而是在运行时解析。 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: 现在,您可以调用Add方法,并在其中添加每个数字,如下所示:

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. 使用dynamic跳过编译时错误。

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]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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