Explanation of C ා generic type knowledge



Generic classes and generic methods have reusability, type safety and efficiency, which can not be realized by non generic classes and non generic methods

Generics are often used with collections and methods that act on them

Generic name space: System.Collections.Generic

You can create custom generic interfaces, generic classes, generic methods, generic events, and generic delegates to provide your own generic solutions and design efficient patterns for type safety

Generics allow you to write a class or method that works with any data type


using System;
using System.Collections.Generic;

namespace GenericTest
  public class TestGeneric<T>

    private T[] array;
    public TestGeneric(int i)
      array = new T[i + 1];
    public T GetItem(int index)
      return array[index];
    public void setItem(int index, T value)
      array[index] = value;

  class Tester
    static void Main(string[] args)
      TestGeneric<char> MyArray = new TestGeneric<char>(5);
      for (int i = 0; i < 5; i++)
        MyArray.setItem(i, (char)(i + 97));

      for (int i=0; i<5; i++)




Limits the types of types that code can use for type parameters when instantiating classes

The way to constrain is to specify the ancestor of T, that is, the inherited interface or class

Code that attempts to instantiate a class with a type that is not allowed by a constraint generates a compile time error

Definition: public t getinfo < T > (string ID) where t: cbaseinfo

Constraints and constraints

T: The struct type parameter must be a value type. You can specify any value type other than nullable

T: The class type parameter must be a reference type, including any class, interface, delegate, or array type

T: A new() type parameter must have a public constructor without parameters. When used with other constraints, the new () constraint must be specified last

T: The < base class name > type parameter must be the specified base class or derived from the specified base class

T: The < interface name > type parameter must be the specified interface or implement the specified interface. Multiple interface constraints can be specified. Constraint interfaces can also be generic.

T: The type parameter provided by u for t must be a parameter provided for u or derived from a parameter provided for u, which is called a naked type constraint

For example:

public class Myarray<T> : B<T> where T : new() { }

Define multiple type parameters and constraints:

public class Base<A,B,C> where A: struct
where B: new()
where C: class
{ }

Generics can also inherit generics:

class D:C<string,int>

class E<U,V>:C<U,V>

class F<U,V>:C<string,int>

The above is the detailed content of C ා generic type knowledge. For more information about C ා generic type, please pay attention to other related articles in developeppaer!