简体   繁体   English

c#创建实例并将元素添加到给定类型的集合中,该类型可以是:数组,列表,字典,队列,堆栈

[英]c# create instance and add elements to a collection given a type, which can be: Arrays, Lists, Dictionaries, Queues, Stacks

I have the following code 我有以下代码

public void example(Type t)
{
    var collector = (ICollection)Activator.CreateInstance(t);

    Debug.Log(collector);
}

this prints 此打印

System.Collections.Generic.List`1[System.Int32]
System.Collections.ArrayList

but I need to add elements 但我需要添加元素


Explaining myself better 更好地自我解释

I have the type of ICollection, I need to take it to a generic structure that allows me to add or insert elements 我有ICollection的类型,我需要将其带入允许我添加或插入元素的通用结构

public void example(Type t){

   var my_collector = new AnyClass((ICollection)Activator.CreateInstance(t));

   collector.Add(new element());
   //or
   collector.insert(new element(),0);
}

but, I'm not interested in printing the elements, this I did to show the types of collectors that will come. 但是,我对打印元素不感兴趣,我这样做是为了展示将要使用的收集器的类型。 I'm only interested in adding or inserting elements in the new ICollector 我只对在新的ICollector中添加或插入元素感兴趣

Anyway, thanks for your answers 无论如何,谢谢您的回答

You can't add elements to an ICollection. 您不能将元素添加到ICollection。 You'll need to downcast 'collector' to IList, Queue, or Stack: 您需要将“收集器”下放到IList,Queue或Stack:

switch (collector)
{
    case IList list:
        list.Add("something");
        break;
    case Queue queue:
        queue.Enqueue("something");
        break;
    case Stack stack:
        stack.Push("something");
        break;
}

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

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