In C # generics and arrays in C #2.0, the one-dimensional array with the lower limit of 0 is automatically implemented by IList <T>. This allows you to create generic methods that can access arrays and other collection types cyclically using the same code. This technology is mainly useful for reading data from a set. The IList <T> interface cannot be used to add or remove elements to an array. If you try to call the IList <T> method (such as the RemoveAt of an array) In this context, an exception is thrown. The following code example demonstrates how a single generic method with IList <T> input parameters cyclically accesses the list and array at the same time. In this example, it is an integer array.
C # Generic and array code
Copy codeThe Code is as follows: class Program
{
Static void Main ()
{
Int [] arr = {0, 1, 2, 3, 4 };
List <int> list = new List <int> ();
For (int x = 5; x <10; x ++)
{
List. Add (x );
}
ProcessItems <int> (arr );
ProcessItems <int> (list );
}
Static void ProcessItems <T> (IList <T> coll)
{
Foreach (T item in coll)
{
System. Console. Write (item. ToString () + "");
}
System. Console. WriteLine ();
}
}
C # Notes for generic and array applications
Although the ProcessItems method cannot add or remove items, the IsReadOnly attribute returns False for T [] In ProcessItems because the array itself does not declare the ReadOnly attribute.
The C # Generic and array-related content will be introduced here, hoping to help you understand and learn C # generics and arrays.