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

推荐订阅源

D
DataBreaches.Net
IT之家
IT之家
博客园_首页
博客园 - 【当耐特】
V
V2EX
Apple Machine Learning Research
Apple Machine Learning Research
G
Google Developers Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recent Announcements
Recent Announcements
F
Fortinet All Blogs
GbyAI
GbyAI
腾讯CDC
H
Hackread – Cybersecurity News, Data Breaches, AI and More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ
H
Help Net Security
T
Tailwind CSS Blog
B
Blog RSS Feed
Martin Fowler
Martin Fowler
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
博客园 - 叶小钗
雷峰网
雷峰网
量子位

博客园 - Nillson

传说中的Singleton.... 设计模式--简单工厂模式 策略模式 抽象类与接口 C# 实现的一个二叉树类 回顾一个面试题 常见的排序方法 预定义,宏定义 连接符,数值运算与函数 复杂查询 数据库中的Index和View的理解 重载和重写 采用递归的方法获得一棵树的所有叶节点 .NET中的新概念整理 4月要看的书 System.Runtime.InteropServices浅见 挂个牛人 一篇关于如何写注释的文章,值得收藏 Vistual Studio 2005到Vistual Studio 2008的版本转换问题 Visual Studio 2008 的一个Bug
再谈代理
Nillson · 2008-07-08 · via 博客园 - Nillson

代理类似于C++中的函数指针,其作用都是为了完成对某一个函数细节的调用,但是函数指针破坏了类的封装性原则,而代理则是类型安全的,也维护了类的封装性。

代理的对象可以是一个命名过的方法或者是匿名的方法,但是在代理的过程中,方法的参数和返回值一定要和代理的参数和返回值相符合。假如我们声明这样的一个代理

public delegate void VoidDelegate(string str);

那么意味着这个代理只能代理返回值为void的并且带有一个string类型参数的方法,不满足这两个条件中的任何一个,在编译时候都不可能通过。

另外代理还支持匿名代理。如下面这段代码:

VoidDelegate v2 = delegate(string str)
{
       Console.WriteLine(str);
};//注意这个分号

在这里由于VoidDelegate是带一个string参数但是没有返回值的代理,在匿名代理的实现中就没有返回值。

如果我们声明了这样的一个代理:

public delegate string VoidDelegate(string str);

那么我们这段匿名代理就需要写成这样:

VoidDelegate v2 = delegate (string str)
{
        Console.WriteLine(str);
        return str;
};//同样注意这个分号

匿名代理不需要显式的指明返回类型,但是需要在方法里边返回一个string类型的值。

附一段测试的code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public delegate string VoidDelegate(string str);
    class DelegateTest
    {
        public static void Main()
        {
            DelegateTest dt = new DelegateTest();
            dt.Execute();
        }
        public static string Method1(string str)
        {
            Console.WriteLine(str);
            return str;
        }
        public void Execute()
        {
            VoidDelegate v1 = Method1;
            VoidDelegate v2 = delegate (string str)
            {
                Console.WriteLine(str);
                return str;
            };
            v1("hello");
            v2("World");
        }
    }
}