您的位置:首页 > 编程语言 > C#

C#的委托区别 Action,Func, Predicate

2014-05-10 15:15 330 查看
Action无返回值4种重载

Action<T>

Action<T1,T2>

Action<T1,T2,T3>

Action<T1,T2,T3,T4>

用于执行一个带参数的操作,并且不返回值。

示例如下以Action<T>为例

public static void Main()
{
Action<string> messageTarget;

//方法是实例化 Action<T> 委托,而不是显式定义一个新委托并将命名方法分配给该委托。
messageTarget = ShowWindowsMessage;
messageTarget("Hello, World1!");

// Action<T> 委托与匿名方法一起使用
messageTarget = delegate(string s) {ShowWindowsMessage(s); };
messageTarget("Hello, World2!");

//将 lambda 表达式分配给 Action<T> 委托实例
messageTarget = s => ShowWindowsMessage(s);
messageTarget("Hello, World3!");
}

private static void ShowWindowsMessage(string message)
{
MessageBox.Show(message);
}


Func返回值保存在TResult中5种重载,同时Func的返回类型也为TResult

Func<TResult>

Func<T,TResult>

Func<T1,T2,TResult>

Func<T1,T2,T3,TResult>

Func<T1,T2,T3,T4,TResult>

用于执行一个带参数的操作,并且有返回值,返回值保存在TResult中。

示例如下以Func<T,TResult>为例

public static void Main()
{
// 实例化 Func<T, TResult> 委托
Func<string, string> convertMethod = UppercaseString;
string name = "Dakota1";
Console.WriteLine(convertMethod(name));

//将 Func<T, TResult> 委托与匿名方法一起使用
Func<string, string> convert = delegate(string s)
{ return UppercaseString(s);};

string name = "Dakota2";
Console.WriteLine(convert(name));

//将 lambda 表达式分配给 Func<T, TResult> 委托。
Func<string, string> convert = s => UppercaseString(s);
string name = "Dakota";
Console.WriteLine(convert(name));
}

private static string UppercaseString(string inputString)
{
return inputString.ToUpper();
}


Predicate<T>返回值为bool无重载,顾名思义用于对象比较,多用于在集合中搜索元素。

static void Main(string[] args)
{      string Text = "abcdefg";      //实例化Predicate<string> 委托      Predicate<string> FindA;
FindA = ContainA;
Console.WriteLine(FindA(Text));
//将 Predicate<string> 委托与匿名方法一起使用      FindA = delegate(string s) { return ContainA(s); };      Console.WriteLine(FindA(Text));

    //将 lambda 表达式分配给 Predicate<string> 委托。
FindA = s=>ContainA(s);      Console.WriteLine(FindA(Text));}
public static bool ContainA(string Text){
return Text.IndexOf("a") > 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: