在Action<Of T>基础上增加了返回值,其参数原型如下:
public delegate TResult Func<in T, out TResult>(
T arg
)
/*
In T
此委托封装的方法的参数类型。
该类型参数是逆变的。即可以使用指定的类型或派生程度更低的类型。有关协变和逆变的更多信息,请参见泛型中的协变和逆变。
Out TResult
此委托封装的方法的返回值类型。
该类型参数是协变的。即可以使用指定的类型或派生程度更高的类型。有关协变和逆变的更多信息,请参见泛型中的协变和逆变。
T arg
)
/*
In T
此委托封装的方法的参数类型。
该类型参数是逆变的。即可以使用指定的类型或派生程度更低的类型。有关协变和逆变的更多信息,请参见泛型中的协变和逆变。
Out TResult
此委托封装的方法的返回值类型。
该类型参数是协变的。即可以使用指定的类型或派生程度更高的类型。有关协变和逆变的更多信息,请参见泛型中的协变和逆变。
*/
以前Delegate方法:
using System;
using System.Windows.Forms;
public delegate string DisplayMessage(string message);
public class testTestDelegate
{
public static void Main()
{
DisplayMessage showMethod = DisplayToWindow;
Console.WriteLine("Return Value:" + showMethod("ZHANGPS"));
Console.ReadLine();
}
public static string DisplayToWindow(string strName)
{
MessageBox.Show("Antiquity Way:Hello World," + strName);
return ("Antiquity Way:Hello World," + strName);
}
using System.Windows.Forms;
public delegate string DisplayMessage(string message);
public class testTestDelegate
{
public static void Main()
{
DisplayMessage showMethod = DisplayToWindow;
Console.WriteLine("Return Value:" + showMethod("ZHANGPS"));
Console.ReadLine();
}
public static string DisplayToWindow(string strName)
{
MessageBox.Show("Antiquity Way:Hello World," + strName);
return ("Antiquity Way:Hello World," + strName);
}
}
Func方法:
using System;
using System.Windows.Forms;
public class testTestDelegate
{
public static void Main()
{
Func<string,string> showMethod = DisplayToWindow;
Console.WriteLine("Return Value:" + showMethod("ZHANGPS"));
Console.ReadLine();
}
public static string DisplayToWindow(string strName)
{
MessageBox.Show("Action Way:Hello World," + strName);
return ("Action Way:Hello World," + strName);
}
using System.Windows.Forms;
public class testTestDelegate
{
public static void Main()
{
Func<string,string> showMethod = DisplayToWindow;
Console.WriteLine("Return Value:" + showMethod("ZHANGPS"));
Console.ReadLine();
}
public static string DisplayToWindow(string strName)
{
MessageBox.Show("Action Way:Hello World," + strName);
return ("Action Way:Hello World," + strName);
}
}
更简化方法(Func还可以传递多个参数,请查阅MSDN):
using System;
using System.Windows.Forms;
public class testTestDelegate
{
public static void Main()
{
Func<string,string> showMethod = s =>{
MessageBox.Show("Action Way:Hello World," + s);
return ("Action Way:Hello World," + s);
};
string strName = "ZHANGPS";
Console.WriteLine(showMethod(strName));
Console.ReadLine();
}
using System.Windows.Forms;
public class testTestDelegate
{
public static void Main()
{
Func<string,string> showMethod = s =>{
MessageBox.Show("Action Way:Hello World," + s);
return ("Action Way:Hello World," + s);
};
string strName = "ZHANGPS";
Console.WriteLine(showMethod(strName));
Console.ReadLine();
}
}