C# 委托 简单说两句

2012-03-23  金城  2076

学习C# 的时候委托曾经把我搞的晕头转向,还以为是神马新鲜东西呢。如果你在学习中也喜欢转圈。希望下面的对比会给你带来帮助。

如果你熟悉VB/vbs/asp,C,JavaScript,Delphi,php等任意一种就可以通过比较来了解 C#的委托。

例如 C#中的委托

public delegate void SomeFuncDelegate(string name);

class Program{

private static void abc(string msg){
    Console.WriteLine("abc:"+msg);
  }

private static void def(string msg){
    Console.WriteLine("abc:"+msg);'' WinForm可以中用 MessageBox.Show(msg);
  }

  private static void MsgFunc(string msg,SomeFuncDelegate DoSomeFunc){
DoSomeFunc(msg);
}

  static void Main(string[] args){
    MsgFunc("哈哈",abc);//输出 abc:哈哈
  }

}

下边都基本上都能通过模拟实现,词语不一样,理是一样的,有的叫委托,有的叫回调,有的叫指针,有的宏替换/代换。

到底怎么用?具体问题具体对待。一定要注意无数前辈的共识:

委托 能够大大简化在某些特定的场合调用多个相同形式函数的处理,并使得程序具有更好的可扩展性;
或者说当一个对象包含复杂单独立的,必须基于判决执行的功能性的若干部分时,最佳的方法是适用基于委托设计模式的对象。
了解这个含义,灵活运用,切记不要死板。

与vb/vbs/asp 对比,vb之类的可以用 Execute 或 Eval 或更厉害的 ExecuteGlobal,与C#的区别是不用申明 委托

例如:

sub abc(msg)
msgbox "abc:"&msg '' asp 中换成 Response.write("abc:"&msg) 或换成 response.write("<"&"script>alert('abc:"&msg &"')</script>")
end sub

sub def(msg)
msgbox "def:"&msg
end sub

sub MsgFunc(f,msg)
Execute f &""""&msg &""""
end sub

MsgFunc "abc","哈哈"

与C对比在C中早就有 callback,指针函数之类,当然这个和C#的委托还是有很大区别,一般都做个模仿C#的委托,代码超长。

与DELPHI对比

unit Unit1;

interface

uses
Windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls;

type
TSomeFuncDelegateClass=procedure(msg:string) of object;//定义一个委托
{...此处省略1024字...}
private
procedure abc(msg:string);
procedure def(msg:string);
procedure DoMsgFunc(Delegate:TSomeFuncDelegateClass;msg:string);
{...此处省略八万四千字...}

var
Form1:TForm1;

implementation

{...此处又发生了省略事件,不过该懂的一定懂的...}

procedure TForm1.abc(msg:string);
begin
MessageBox('abc:'+msg);
end;

procedure TForm1.def(msg:string);
begin
MessageBox('def:'+msg);
end;

procedure TForm1.DoMsgFunc(Delegate:TSomeFuncDelegateClass;msg:string);
begin
if Assigned(Delegate) then Delegate(msg);
end;

procedure TForm1.Button1Click(Sender:TObject);
begin
DoMsgFunc(abc,'哈哈');
end;

与JavaScript对比,也免了声明了,可以回调,也可以eval,还可以模拟C#,太灵活了

//用在网页中(DOM)
function abc(msg){alert('abc:'+msg);};
function def(msg){alert('def:'+msg);};
function someFunc(f,msg){f(msg);};
someFunc(abc,"哈哈");
// eval("abc('哈哈');")

与PHP对比call_user_func,call_user_func_array,forward_static_call 等等等,可以回调,可以模拟

<?php
function abc($msg){echo "abc:$msg";}
function def($msg){echo "def:$msg";}
call_user_func('abc','哈哈');