C# 委托的编译器处理
如果我宣布一名代表C# 委托的编译器处理,c#,delegates,C#,Delegates,如果我宣布一名代表 public delegate void firstDelegate(string str); firstDelegate handler = Strfunc; handler("Hello World"); .. static void Strfunc(string str) { Console.WriteLine(str); } 编译器会翻译下面这行吗 firstDelegate handler=Strfunc; 进入 到目前为止
public delegate void firstDelegate(string str);
firstDelegate handler = Strfunc;
handler("Hello World");
..
static void Strfunc(string str)
{
Console.WriteLine(str);
}
编译器会翻译下面这行吗
firstDelegate handler=Strfunc;
进入
到目前为止,我可以说,是的 这称为“委托推理” 顺便说一句,如果您想将另一个函数“附加”到此委托,请使用: handler+=另一个函数名 以下是《专业-C#-2008》一书第7章中C#专业人士的话: 为了减少键入,在每个需要委托实例的地方,只需传递委托实例的名称即可 地址。这被称为委托推理。只要编译器能够,这个C#特性就可以工作 将委托实例解析为特定类型。 C#编译器创建的代码是相同的。编译器检测到委托类型为 必需,因此它创建该委托类型的实例并
将方法的地址传递给构造函数。没错。以下是从反射器的拆卸:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 3
.locals init (
[0] class ConsoleApplication4.Program/firstDelegate handler)
L_0000: nop
L_0001: ldnull
L_0002: ldftn void ConsoleApplication4.Program::Strfunc(string)
L_0008: newobj instance void ConsoleApplication4.Program/firstDelegate::.ctor(object, native int)
L_000d: stloc.0
L_000e: ldloc.0
L_000f: ldstr "Hello World"
L_0014: callvirt instance void ConsoleApplication4.Program/firstDelegate::Invoke(string)
L_0019: nop
L_001a: ret
}
在C#中是这样的:
所以对于所有函数,我只传递一条消息。我的意思是,我可以传递不同的消息吗,一条用于func1,另一条用于func2?恐怕不行。multicase委托,您可以将其视为一组按该顺序执行的函数,每个函数都使用相同的函数表进行传递。因此,它们都处理相同的参数。这是一个在处理GUI时非常有用的技巧,因为一个特定事件可能会触发多个侦听器(处理程序对象)做出反应;您仍然可以看到许多使用详细表单的代码,并且仍然有许多自动代码生成器生成它。谢谢Eric Lippert,顺便说一下,CLR到C#将是了解所有这些的合适人选?
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 3
.locals init (
[0] class ConsoleApplication4.Program/firstDelegate handler)
L_0000: nop
L_0001: ldnull
L_0002: ldftn void ConsoleApplication4.Program::Strfunc(string)
L_0008: newobj instance void ConsoleApplication4.Program/firstDelegate::.ctor(object, native int)
L_000d: stloc.0
L_000e: ldloc.0
L_000f: ldstr "Hello World"
L_0014: callvirt instance void ConsoleApplication4.Program/firstDelegate::Invoke(string)
L_0019: nop
L_001a: ret
}
private static void Main(string[] args)
{
firstDelegate handler = new firstDelegate(Program.Strfunc);
handler("Hello World");
}