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

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

我有以下代码

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

    Debug.Log(collector);
}

这会打印

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

但我需要添加元素


更好地解释自己

我有 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);
}

但是,我对打印这些元素不感兴趣,我这样做是为了展示即将到来的收藏家的类型。 我只对在新的 ICollector

中添加或插入元素感兴趣

无论如何,谢谢你的回答

您不能向 ICollection 添加元素。您需要将 'collector' 向下转换为 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;
}