csharp_语法点训练_记录
委托
有什么用?
变量:数据;
方法:行为;
delegate
委托需要声明委托,实例化委托,调用委托三个步骤;
函数可以使用匿名函数:毕竟
action 和fun
泛型有关;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
delegate void output(string msg);
public void output_fun(string msg) { Console.WriteLine(msg); } [TestMethod] public void test_delegate() { output ot = output_fun; ot("委托");
output ot2 = delegate (string name) { Console.WriteLine($"{name}"); }; ot2("anonymous method");
output ot3 = name => Console.WriteLine($"{name}");
#region 委托的变体 向上/下转型的一种容纳 https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/covariance-contravariance/variance-in-delegates #endregion
Action<string> actStr = x => Console.WriteLine("string: {0}", x); Func<string, string> actFunc = x => "3";
}
|
扩展方法允许开发人员往一个现有的CLR类型的公开契约(contract)中添加新的方法,而不用生成子类或者重新编译原来的类型。扩展方法有助于把今天动态语言中流行的对duck typing的支持之灵活性,与强类型语言之性能和编译时验证融合起来。
