上次用到了比较老的 delege 委托,新的升级中有新的关键字 Action 和Func
1,Action,可以传入参数,没有返回值的委托!
看看函数重载说明就知道了!上代码,一目了然
static void Main(string[] args)
{
Action<int, int> action = new Action<int, int>(addVoid); // Action<int, int> 这就是方法的原型
action(1, 2);
action.Invoke(2, 3); //基本的使用方法和delege都是差不多的,包括异步的写法也是相同的,
//但是他升级了,厉害之处是加入了lamda, Action<int, int>就是声明委托原型 简化了写法,通过lamda (n,m)=>{} 匿名函数的写法
Action<int, int> actionOne = new Action<int, int>((n, m) =>
{
Console.WriteLine("lamda方式1 计算结果{0}", (n + m));
});
actionOne.Invoke(4, 5);
//lamda 搞法很优雅
Action<int, int> actionTwo = (n, m) =>
{
Console.WriteLine("lamda方式2 计算结果{0}", (n + m));
};
actionTwo.Invoke(3, 4);
Console.ReadKey();
}
static void addVoid(int a, int b)
{
Console.WriteLine("计算结果{0}", (a + b));
}
运行情况
2,Func用法,他跟Action 的区别是可以有返回值
out 这个是输出参数,简单来说就是我们的返回值,重载很多的时候,最后一个就是,可以敲看看
static void Main(string[] args)
{
Func<int> func = new Func<int>(ReturnOne); //一个参数时候,就是返回值(无参数,有返回值),Func<int>这就是方法的原型了
int res = func.Invoke();
Console.WriteLine(" 计算结果{0}", res);
Func<int> funcOne = () =>
{
return 1;
};
int resOne = funcOne.Invoke();
Console.WriteLine("lamda方式1 计算结果{0}", res);
Func<int> funcTwo = new Func<int>(() =>
{
return 2;
});
int resTwo = funcTwo.Invoke();
Console.WriteLine("lamda方式2 计算结果{0}", resTwo);
Func<int, int, int> funcThree = (n, m) =>
{
return n + m;
};
int resThree = funcThree.Invoke(1, 2); //参数只两个,最后的一个参数也是int,不过是输出参数,也就是返回值
Console.WriteLine("lamda方式3 计算结果{0}", resThree);
Func<int, int, int> funcFour = new Func<int, int, int>(add);
int resFour = funcThree.Invoke(1, 3); //调用封装好的方法
Console.WriteLine("lamda方式4 计算结果{0}", resFour);
Console.ReadKey();
}
static int add(int a, int b)
{
return a + b;
}
static int ReturnOne()
{
return 1;
}
}
比较简单,欢迎指教!
委托除了在线程中更新UI调用之外, 还可以在UI之间传值是使用
简单的例子:
代码入下
public Form1()
{
InitializeComponent();
this.button1.Enabled = false;
}
Form2 form2;
private void button1_Click(object sender, EventArgs e)
{
var res = form2.SetValues2("你好"); //,调用委托
MessageBox.Show("返回值:" + res.ToString()); //show出返回值
}
private void button2_Click(object sender, EventArgs e)
{
form2 = new Form2();
form2.Show();
this.button1.Enabled = true;
}
窗体2的代码
public bool SetValues2(string ast)
{
//Func<string, bool> RetBook = new Func<string, bool>((a)=> {
// myTxtBox.Text = a;
// return true;
//});
Func<string, bool> RetBook = (a) =>
{
myTxtBox.Text = a;
return true;
};
return RetBook(ast);
}
这里简单使用了func委托,Action同样也是可以的,写法十分优雅!