新建一泛型委托类GenericDelegate.cs ,在里面进行委托的定义
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpAdvancedDelegate
{
delegate void GenericDelegate1<T>(T t);
public class GenericDelegate
{
public static void InvokeDelegate()
{
GenericDelegate1<string> genericDelegate = new GenericDelegate1<string>(Method1);
GenericDelegate1<int> genericDelegate2 = new GenericDelegate1<int>(Method2);
genericDelegate("我是泛型委托1");
genericDelegate2(23);
}
/// <summary>
/// 泛型委托方法1
/// </summary>
/// <param name="str"></param>
public static void Method1(string str)
{
Console.WriteLine(str) ;
}
/// <summary>
/// 泛型委托方法2
/// </summary>
/// <param name="str"></param>
public static void Method2(int str)
{
Console.WriteLine(str);
}
}
}
在Program.cs类中的Main函数中添加以下代码
static void Main(string[] args)
{
Console.WriteLine("=================泛型委托=================");
GenericDelegate.InvokeDelegate();
Console.Read();
}
系统自带的委托的应用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpAdvancedDelegate
{
public class GenericDelegate
{
public static void InvokeDelegate()
{
//系统自带的无返回值委托
Action<string> action = new Action<string>(Method1); //填写的是方法名
action("我是泛型委托1"); //填写的是方法中的参数
//一个是参数一个是返回值
Func<string, string> func = new Func<string, string>(Method3);
Console.WriteLine(func("有返回值有参数的泛型委托"));
}
/// <summary>
/// 泛型委托方法1
/// </summary>
/// <param name="str"></param>
public static void Method1(string str)
{
Console.WriteLine(str) ;
}
/// <summary>
/// 泛型委托方法2
/// </summary>
/// <param name="str"></param>
public static void Method2(int str)
{
Console.WriteLine(str);
}
/// <summary>
/// 有返回值有参数的泛型委托方法3
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Method3(string str)
{
return str;
}
}
}
在Main()函数中的调用
static void Main(string[] args)
{
Console.WriteLine("=================泛型委托=================");
GenericDelegate.InvokeDelegate();
Console.Read();
}