C# Generics
Kiểu mảng cũ
using System;
using System.Collections;
namespace TestApp {
class Test {
[STAThread]
static void Main(string[] args) {
ArrayList list = new ArrayList();
list.Add(3);
list.Add(4);
//list.Add(5.0);
int total = 0;
foreach(int val in list) {
total = total + val;
}
Console.WriteLine( “Total is {0}”, total);
}
}
}
Generics
List<int> aList = new List<int>();
aList.Add(3);
aList.Add(4);
// aList.Add(5.0);
int total = 0;
foreach(int val in aList) {
total = total + val;
}
Console.WriteLine(“Total is {0}”, total);
Viết generics class
//MyList.cs
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace CLRSupportExample {
public class MyList<T> {
private static int objCount = 0;
public MyList() { objCount++; }
public int Count {
get { return objCount; }
}
}
}
//Program.cs
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace CLRSupportExample {
class SampleClass {}
class Program {
static void Main(string[] args) {
MyList<int> myIntList = new MyList<int>();
MyList<int> myIntList2 = new MyList<int>();
MyList<double> myDoubleList = new MyList<double>();
MyList<SampleClass> mySampleList = new MyList<SampleClass>();
Console.WriteLine(myIntList.Count);
Console.WriteLine(myIntList2.Count);
Console.WriteLine(myDoubleList.Count);
Console.WriteLine(mySampleList.Count);
Console.WriteLine( new MyList<sampleclass>().Count);
Console.ReadLine();
}
}
}
Methods với Generics
public class Program {
public static void Copy<T>(List<T> source, List<T> destination){
foreach (T obj in source) {
destination.Add(obj);
}
}
static void Main(string[] args)
{
List<int> lst1 = new List<int>();
lst1.Add(2);
lst1.Add(4);
List<int> lst2 = new List<int>();
Copy(lst1, lst2);
Console.WriteLine(lst2.Count);
}
}