简介:
封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。
介绍:
类型参数 in T | 此委托封装的方法的参数类型。 |
类型参数 out TResult | 此委托封装的方法的返回值类型。 |
参数 T arg | 此委托封装的方法的参数。 |
返回值 TResult | 此委托封装的方法的返回值。 |
使用:
1.显式声明了一个名为 ConvertMethod 的委托,并将对 UppercaseString 方法的引用分配给其委托实例。
using System;
//声明一个委托
delegate string ConvertMethod(string inString);
public class DelegateExample
{
public static void Main()
{
// 实例化委托以引用UppercaseString方法
ConvertMethod convertMeth = UppercaseString;
string name = "Dakota";
// 使用委托实例调用UppercaseString方法
Console.WriteLine(convertMeth(name));
}
private static string UppercaseString(string inputString)
{
return inputString.ToUpper();
}
}
2.实例化 Func< T, TResult> 委托,而不是显式定义一个新委托并将命名方法分配给该委托。
using System;
public class GenericFunc
{
public static void Main()
{
// 实例化委托以引用UppercaseString方法
Func<string, string> convertMethod = UppercaseString;
string name = "Dakota";
// 使用委托实例调用UppercaseString方法
Console.WriteLine(convertMethod(name));
}
private static string UppercaseString(string inputString)
{
return inputString.ToUpper();
}
}
3.Func< T, TResult> 委托与匿名方法一起使用。
using System;
public class Anonymous
{
public static void Main()
{
//Func委托与匿名方法一起使用
Func<string, string> convert = delegate(string s)
{ return s.ToUpper();};
string name = "Dakota";
Console.WriteLine(convert(name));
}
}
4.lambda 表达式分配给 Func< T, TResult> 委托
using System;
public class LambdaExpression
{
public static void Main()
{
//Func委托与lambda一起使用
Func<string, string> convert = s => s.ToUpper();
string name = "Dakota";
Console.WriteLine(convert(name));
}
}
5.声明一个 Func< T, TResult> 变量,并为其分配了一个将字符串中的字符转换为大写的 lambda 表达式。随后将封装此方法的委托传递给 Enumerable. Select 方法,以将字符串数组中的字符串更改为大写。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
static class Func
{
static void Main(string[] args)
{
// 声明一个Func变量并将lambda表达式赋值给变量。该方法是把一个字符串并将其转换为大写。
Func<string, string> selector = str => str.ToUpper();
// 创建一个字符串数组
string[] words = { "orange", "apple", "Article", "elephant" };
// 查询数组并根据Select选择器方法选择字符串。
IEnumerable<String> aWords = words.Select(selector);
// 输出
foreach (String word in aWords)
Console.WriteLine(word);
}
}