C#之Action/Func/out/ref/params/类型参数约束
Action的用法:
using System;
using System.Collections.Generic;
class Program {
/// <summary>
/// 输出字符串
/// </summary>
static void PrintString()
{
Console.WriteLine("hello world.");
}
/// <summary>
/// 输出整数
/// </summary>
/// <param name="i">整数</param>
static void PrintInt(int i)
{
Console.WriteLine(i);
}
static void Main(string[] args)
{
Action a = PrintString;//action是系统内置(预定义)的一个委托类型,它可以指向一个没有返回值,没有参数的方法
Action<int> b = PrintInt;//定义了一个委托类型,这个类型可以指向一个没有返回值,有一个int参数的方法
a();
b(100);
Console.ReadKey();
}
}
Func的用法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static int Test1()
{
return 1;
}
static bool Test(int x)
{
if (x== 0)
{
return true;
}
else
{
return false;
}
}
static int Test2(string str)
{
Console.WriteLine(str);
return 100;
}
static int Test3(int i, int j)
{
return i + j;
}
static void FunctionTest(bool x)
{
if (x)
{
Console.WriteLine("this is 零!");
}
else
{
Console.WriteLine("this is 非零!");
}
}
static void Main(string[] args)
{
Func<int> a = Test1;//func中的泛型类型制定的是 方法的返回值类型
Func<string, int> b = Test2;//func后面可以跟很多类型,最后一个类型是返回值类型,前面的类型是参数类型,参数类型必须跟指向的方法的参数类型按照顺序对应
Func<int, int, int> c = Test3;//func后面必须指定一个返回值类型,参数类型可以有0-16个,先写参数类型,最后一个是返回值类型
Func<int,bool> f = Test;
Console.WriteLine(a());
Console.WriteLine(b("husheng"));
Console.WriteLine(c(123, 456));
Program.FunctionTest(f(0));
Program.FunctionTest(f(1));
Console.ReadKey();
}
}
关于回调函数的理解:就好比你在网上买某个东西,可是这个东西暂时没货,于是你就把你的电话号码留在网上,到货的时候网站会自动给你发信息提醒到货了。那么,你的电话就相当于回调函数,回调函数执行的结果就是你收到了"到货"的通知。然后你根据这个通知,再决定要不要买。
ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。
out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于ref 要求变量必须在传递之前进行初始化。
方法定义和调用方法都必须显式使用 out 关键字。
属性不是变量,因此不能作为 out 参数传递。
params类型的参数搭配数组使用,实现一个不定长的数组参数。
类型参数约束,.NET支持的类型参数约束有以下五种:
where T : struct | T必须是一个结构类型
where T : class | T必须是一个类(class)类型,不能是结构(structure)类型
where T : new() | T必须要有一个无参构造函数
where T : NameOfBaseClass | T必须继承名为NameOfBaseClass的类
where T : NameOfInterface | T必须实现名为NameOfInterface的接口
====================================================================================
结束。