最後に、新しいアップグレード新しいキーワードアクションとのFunc委託古いdelege使用
信頼の戻り値なし1は、アクションは、パラメータを渡すことができます!
知っ示しオーバーロードされた関数を見てください!一目でコード
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の使用状況、彼とアクションが値を返すことができるとの違い、
このうちは、出力パラメータであり、多くの時間をオーバーロード、単に私たちの戻り値で、最後の一つは、あなたが見てノックすることができるということです
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デリゲートを使用して、アクションも可能で、言葉遣いは非常にエレガントです!