How are generic collections defined in C#?

In C#, a method can be defined using a generic collection. Generic collections are collections where the element type can be determined at runtime.

The syntax for defining methods is as follows:

public void methodName<T>(List<T> list)
{
    // 方法体
}

In the above method definition, methodName represents the name of the method, indicates that the method is a generic method with T as a type parameter. List is the type of a generic collection, and list is a parameter of the method.

Within the body of the method, you can operate on the list, such as adding, deleting, modifying, and accessing elements in the collection.

The advantage of using generic methods is the ability to perform different types of operations in various places with the same method without the need to redefine a method for each type. This improves code reusability and maintainability.

Here is an example of a method defined using a generic collection.

public void PrintList<T>(List<T> list)
{
    foreach (T item in list)
    {
        Console.WriteLine(item);
    }
}

In the example above, the PrintList method can take any type of generic collection as a parameter and print each element in the collection. Additional operations can be added to the method body as needed.

bannerAds