Action委托
注意点
- Action委托只能指向无参数,无返回值的方法
示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace study3
{
class Program
{
static void Main(string[] args)
{
Action myAction = new Action(SayHello);
myAction();
}
static void SayHello()
{
Console.WriteLine("Hello");
}
}
}
Func委托
示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace study_5
{
class Program
{
static void Main(string[] args)
{
Cal cal = new Cal();
Func<int, int, int> func1 = new Func<int, int, int>(cal.Add);
int result = func1(2, 3);
Console.WriteLine(result);
}
}
class Cal
{
public int Add(int n1,int n2)
{
return n1 + n2;
}
}
}
自定义委托
示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace study_5
{
public delegate string StrConnect(string str1, string str2);
class Program
{
static void Main(string[] args)
{
StrTools strTools = new StrTools();
string str1 = "你好,";
string str2 = "世界!";
StrConnect tools = new StrConnect(strTools.StrCon);
string str3 = tools(str1, str2);
Console.WriteLine(str3);
}
}
class StrTools
{
public string StrCon(string str1, string str2)
{
return str1 + str2;
}
}
}
应该适时地使用接口(interface)取代一些对委托的使用