c# generics (generic)

Overview:

Generics in C# are a mechanism that allows the use of parameterized types when writing classes, methods, and delegates. Generics allow us to write more general, reusable code, avoiding type conversions and rewriting similar code.

The basic syntax of generics is as follows:

class ClassName<T>
{
    
    
    // 泛型类的定义
}

void MethodName<T>(T parameter)
{
    
    
    // 泛型方法的定义
}

In a generic class or method, T is a type parameter that can be used to define the fields of the class, the parameters of the method, and the return type.

Here are a few common examples of using generics:

Generic class:

class GenericClass<T>
{
    
    
    private T value;

    public GenericClass(T value)
    {
    
    
        this.value = value;
    }

    public T GetValue()
    {
    
    
        return value;
    }
}

GenericClass<int> intObject = new GenericClass<int>(5);
int intValue = intObject.GetValue();

GenericClass<string> stringObject = new GenericClass<string>("Hello");
string stringValue = stringObject.GetValue();

Generic methods:

T Max<T>(T a, T b)
{
    
    
    return a.CompareTo(b) > 0 ? a : b;
}

int maxInt = Max<int>(5, 3);
string maxString = Max<string>("apple", "banana");

Generic passing:

//The subclass is also not sure of the specific type, and passes the type to the place where generic specialization is needed later.

        public class person<T>
        {
    
    
            public T Name {
    
     get; set; }
        }
        //泛型方法中也可以定义多个泛型
        public class teacher<T, U> : person<T>
        {
    
    
            public U date {
    
     get; set; }

            public override string? ToString()
            {
    
    
                string str = "";
                str += $"name:{
      
      Name}\n";
                str += $"date:{
      
      date}";
                return str.ToString();
            }
        }
        private static void Main(string[] args)
        {
    
    
            teacher<string, int> t1 = new teacher<string, int>();
            t1.Name = "xiaoming";
            t1.date = 2023;
            Console.WriteLine(t1.ToString());
        }

Generic constraints (Constraints) allow us to restrict generic type parameters and specify conditions that type parameters must meet. For example, you can use the where keyword to restrict the type parameter to a certain base class, interface, or parameterless constructor.

Generic constraint example:

class GenericClass<T> where T : IComparable
{
    
    
    // T必须实现IComparable接口
}

T Max<T>(T a, T b) where T : IComparable
{
    
    
    // T必须实现IComparable接口
}

class MyClass<T> where T : new()
{
    
    
    // T必须具有无参数构造函数
}

In addition to classes and methods, C# also supports generic interfaces and generic delegates. Generic interfaces and generic delegates are used in a similar way to generic classes and methods.

Advantages of generics include code reuse, type safety, performance optimization, and better readability. By using generics, we can write more flexible and versatile code, improving the maintainability and scalability of the code.

Guess you like

Origin blog.csdn.net/qq_41942413/article/details/132614021