📜  C#|将一个对象添加到Collection的末尾<T>

📅  最后修改于: 2021-05-29 17:18:11             🧑  作者: Mango

Collection < T > .Add(T)方法用于将一个对象添加到Collection < T >的末尾。

句法 :

public void Add (T item);

这里, item是要添加到Collection < T >末尾的对象。对于引用类型,该值可以为null。

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to add an object to
// the end of the Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a collection of strings
        Collection myColl = new Collection();
  
        myColl.Add("A");
        myColl.Add("B");
        myColl.Add("C");
        myColl.Add("D");
        myColl.Add("E");
  
        // Displaying the number of elements in Collection
        Console.WriteLine("The number of elements in myColl are : " 
                                                   + myColl.Count);
  
        // Displaying the elements in Collection
        Console.WriteLine("The elements in myColl are : ");
  
        foreach(string str in myColl)
        {
            Console.WriteLine(str);
        }
    }
}

输出:

The number of elements in myColl are : 5
The elements in myColl are : 
A
B
C
D
E

范例2:

// C# code to add an object to
// the end of the Collection
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a collection of ints
        Collection myColl = new Collection();
  
        myColl.Add(2);
        myColl.Add(3);
        myColl.Add(4);
        myColl.Add(5);
  
        // Displaying the number of elements in Collection
        Console.WriteLine("The number of elements in myColl are : "
                                                   + myColl.Count);
  
        // Displaying the elements in Collection
        Console.WriteLine("The elements in myColl are : ");
  
        foreach(int i in myColl)
        {
            Console.WriteLine(i);
        }
    }
}

输出:

The number of elements in myColl are : 4
The elements in myColl are : 
2
3
4
5

笔记:

  • Collection < T >接受null作为引用类型的有效值,并允许重复的元素。
  • 此方法是O(1)操作。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.objectmodel.collection-1.add?view=netframework-4.7.2