How to use generics in C#?

Using generics in C# is very simple. You just need to add angle brackets <> after the name when defining a class, struct, interface, method, etc., and specify the generic type parameter inside the brackets. For example, defining a generic class:

public class GenericClass<T>
{
    public T GenericMethod(T value)
    {
        return value;
    }
}

// 使用泛型类
GenericClass<int> intGenericClass = new GenericClass<int>();
int result = intGenericClass.GenericMethod(10);
Console.WriteLine(result);

In the example above, a generic class called GenericClass is defined with a specified generic type parameter T. An instance of GenericClass is then created and the generic method GenericMethod is called, passing in an integer value and returning that value.

Generics can be used not only in classes but also in structs and interfaces. Generics can also be used in methods by simply adding angle brackets <> after the method name and specifying the type parameter for generics.

In conclusion, using generics in C# is a powerful and flexible technique.

Leave a Reply 0

Your email address will not be published. Required fields are marked *