惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
阮一峰的网络日志
阮一峰的网络日志
云风的 BLOG
云风的 BLOG
D
Docker
Vercel News
Vercel News
IT之家
IT之家
Recent Announcements
Recent Announcements
Last Week in AI
Last Week in AI
V
Visual Studio Blog
Engineering at Meta
Engineering at Meta
腾讯CDC
Google DeepMind News
Google DeepMind News
I
InfoQ
博客园 - 三生石上(FineUI控件)
Apple Machine Learning Research
Apple Machine Learning Research
The GitHub Blog
The GitHub Blog
博客园 - Franky
The Cloudflare Blog
A
About on SuperTechFans
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
T
Tenable Blog
P
Proofpoint News Feed
Recorded Future
Recorded Future
Security Latest
Security Latest
H
Hackread – Cybersecurity News, Data Breaches, AI and More
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 聂微东
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Google Online Security Blog
Google Online Security Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Simon Willison's Weblog
Simon Willison's Weblog
The Last Watchdog
The Last Watchdog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
U
Unit 42
The Hacker News
The Hacker News
Martin Fowler
Martin Fowler
T
Threat Research - Cisco Blogs
NISL@THU
NISL@THU
F
Full Disclosure
M
MIT News - Artificial intelligence
人人都是产品经理
人人都是产品经理
Hugging Face - Blog
Hugging Face - Blog
V
V2EX
Project Zero
Project Zero

博客园 - 默默無語中

类与结构的区别 GridView分页-编辑-删除 DataList修改删除 - 默默無語中 - 博客园 弄了一晚上研究连接字符串,给自己留个清楚的回忆~! - 默默無語中 - 博客园 [数据库连接字符串] SQL Server 2005 Compact Edition 连接字符串 委托对象(收集) [导入]asp.net高级教程(三)-实战篇 [导入]asp.net高级教程(三)-对象 [导入]asp.net高级教程(五)-实战篇(中) [导入].NET之ASPWebApplication快速入门(3) [导入].NET之ASPWebApplication快速入门(2) [导入].NET之ASPWebApplication快速入门(1) [导入].NET之ASPWebApplication快速入门(4) [导入].NET之ASPWebApplication快速入门(5) [导入]asp.NET特写 [导入]亲密接触ASP.Net(1) [导入]亲密接触ASP.Net(3) [导入]亲密接触ASP.Net(4) [导入]亲密接触ASP.Net(2) [导入]亲密接触ASP.Net(6) [导入]亲密接触ASP.Net(5)
委托的笔记(整理)
默默無語中 · 2008-05-07 · via 博客园 - 默默無語中

详细讲解地址:/Files/zskj008/Delegates-and-Events-in-CSharp.pdf
什么是委托

  首先要知道什么是委托,用最通俗易懂的话来讲,你就可以把委托看成是用来执行方法(函数)的一个东西。

如何使用委托
  在使用委托的时候,你可以像对待一个类一样对待它。即先声明,再实例化。只是有点不同,类在实例化之后叫对象或实例,但委托在实例化后仍叫委托。

声明,如:

1    namespace Vczx.ProCSharp.Exc
2    {
3        delegate double MathsOp( double x );
4        //class defination here
5    }

  这就声明了一个委托,意义:任何一个返回值为double,且只有一个形参为double的函数,都可以用这个委托来调用。
  注意:委托的声明位置在namespace里面,类的外面。其实,委托的声明也可以在类的里面,甚至是任何一个可以声明类的地方。
  实例化:
  首先我们要先有一个满足委托声明的方法,假设一个返回一个数的2倍的方法:

1class MathsOperations
2{
3    public static double MultiplyBy2( double value )
4    {
5        return value * 2;
6    }

7}

  有了这样一个方法,我们就可以实例化一个委托了:
MathsOp operation = new MathsOp( MathsOperations.MultiplyBy2 );
  在实例化一个委托时,要给它一个参数,这个参数就是委托执行的方法,它可以是静态方法,也可以是实例方法(这一点有别于函数指针,函数指针只能调用静态
方法),如:
MathsOp operation = new MathsOp( new Class1().Method1 );

在实例化完一个委托之后,就可以用这个委托来调用方法了:
double result = operation( 1.23 );

例子代码:

 1namespace Vczx.ProCSharp.Exc
 2{
 3    delegate double MathsOp( double x );
 4    class Start
 5    {
 6        public class MyDelegate
 7        {
 8            public static double MultiplyBy2( double x )
 9            {
10                return x * 2;
11            }

12        }

13        [STAThread]
14        static void Main(string[] args)
15        {
16            MathsOp operation = new MathsOp( MyDelegate.MultiplyBy2 );
17            double x = 1.23;
18            double result = operation( x );
19            Console.WriteLine( "{0} multiply by 2 is {1}", x, result ); 
20            Console.Read();
21        }

22    }

23}

委托的定义:

委托是一种在对象里保存方法引用的类型,同时也是一种类型安全的函数指针。

委托的优点:

压缩方法的调用。

合理有效地使用委托能提升应用程序的性能。

用于调用匿名方法。

委托的声明:

委托应使用public delegate type_of_delegate delegate_name()的形式来声明。
示例:public delegate int mydelegate(int delvar1,int delvar2)

注意点:可以在不带参数或参数列表的情况下声明委托。

        应当遵循和声明方法一样的语法来声明委托。

使用委托的示例程序:

public delegate double Delegate_Prod(int a,int b);

class Class1
 
{

static double fn_Prodvalues(int val1,int val2)
         
{
          
return val1*val2;
          }

static void Main(string[] args)
 
{   

               
//Creating the Delegate Instance
               Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
              Console.Write(
"Please Enter Values");

              
int v1 = Int32.Parse(Console.ReadLine());
               
int v2 = Int32.Parse(Console.ReadLine());

               
//use a delegate for processing

               
double res = delObj(v1,v2);
               Console.WriteLine (
"Result :"+res);
               Console.ReadLine();

}

 }


示例程序解析:

上面我用一段小程序示范了委托的使用。委托Delegate_Prod声明时指定了两个只接受整型变量的返回类型。同样类中名为fn_Prodvalues的方法也是如此,委托和方法具有相同的签名和参数类型。

Main方法中创建一个委托实例并用如下方式将函数名称传递给该委托实例:

Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);

这样我们就接受了来自用户的两个值并将其传递给委托:

delObj(v1,v2);

在此委托对象压缩了方法的功能并返回我们在方法中指定的结果。

多播委托:

多播委托包含一个以上方法的引用。

多播委托包含的方法必须返回void,否则会抛出run-time exception

使用多播委托的示例程序:

delegate void Delegate_Multicast(int x, int y);

Class Class2

{
static void Method1(int x, int y) {
  Console.WriteLine("You r in Method 1");
}
static void Method2(int x, int y) {
  Console.WriteLine("You r in Method 2");
}
public static void Main()
{
  Delegate_Multicast func = new Delegate_Multicast(Method1);

func += new Delegate_Multicast(Method2);
      func(1,2);             // Method1 and Method2 are called
      func
-= new Delegate_Multicast(Method1);
      func(2,3);             // Only Method2 is called
   }

}    

示例程序解析:

大家可以看到上面的示例程序分别定义了名为method1 method2的两个接受整型参数、返回类型为void的方法。

Main函数里使用下面的声明创建委托对象:

Delegate_Multicast func = new Delegate_Multicast(Method1);

然后使用+= 来添加委托,使用-=来移除委托。

     最后这个是最容易的理解的:

delegate void Eatfood(string food); //委托调用方法
    class Test
    
{
        
private string name;
        
public Test(string name)
        
{
            
this.name = name;
        }

        
public void eat(string food)
        
{
            Console.WriteLine(name 
+ "" + food);
        }


    }

    
class disp
    
{
        
static void Main()
        
{
            
//Test a = new Test();
            
//a.zsfood("西瓜");
            
//a.lsfood("橡胶");
            Test aa = new Test("张三");
            Test bb 
= new Test("李四");
            Eatfood zs 
= new Eatfood(aa.eat);
            Eatfood ls 
= new Eatfood(bb.eat);
            Eatfood eat;
            eat 
= zs + ls;
            eat(
"哈密瓜");
          
        }

    }