關於委託泛型的回撥測試
1:宣告一個Employee類
public class Employee
{
private string name;
private int id;
public Employee(string s, int i)
{
name = s;
id = i;
}
public string Name
{
get { return name; }
set { name = value; }
}
public int ID
{
get { return id; }
set { id = value; }
}
}
2:一個操作實體類的方法類,通過對泛型約束訪問特定的資料型別
在泛型型別定義中,where 子句用於指定對下列型別的約束:這些型別可用作泛型宣告中定義的型別引數的實參。
此方法中型別引數T繼承自Employee類,即該型別T必須把Employee作為該型別的基類,也可以繼承介面並實現這個介面
public delegate void Action<T>(T obj);
public class Test
{
public void Process<T>(T s2, Action<T> process) where T : Employee
{
s2.Name = "weiwei";
process(s2);
}
}
3:泛型回撥,使用泛型可以最大限度的重用程式碼,保護型別安全以及提升效能。
class Program
{
static void Main(string[] args)
{
Employee e = new Employee("hua", 0);
Test t = new Test();
t.Process(e, (c) =>
{
Console.WriteLine(c.Name);
Console.Read();
});
}
}