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

推荐订阅源

P
Proofpoint News Feed
V
V2EX
WordPress大学
WordPress大学
Google DeepMind News
Google DeepMind News
Martin Fowler
Martin Fowler
小众软件
小众软件
Blog — PlanetScale
Blog — PlanetScale
月光博客
月光博客
The Cloudflare Blog
T
Tailwind CSS Blog
H
Help Net Security
腾讯CDC
爱范儿
爱范儿
人人都是产品经理
人人都是产品经理
H
Hackread – Cybersecurity News, Data Breaches, AI and More
The GitHub Blog
The GitHub Blog
Microsoft Security Blog
Microsoft Security Blog
Stack Overflow Blog
Stack Overflow Blog
D
DataBreaches.Net
C
Check Point Blog
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
美团技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

博客园 - skylai

mvc3 小技巧 WCF学习之旅(一)---Hello World. WCF Client configuration Jquery表单验证 Jquery的一些常用信息 二进制、SOAP的序列化及反序列化 简单的Attribute实现. 泛型之泛型约束 C#2.0泛型介绍之简单泛型类。 序列化之XML序列化(一) Vs2005的win form动态生成菜单 强制字符换行CSS版和C#版 js操作xml 读写XML文件 js的一些杂谈 一个button同时执行多个有返回值的函数的解决方法(return false; or return true;) DataGrid里应用radio单选按钮 限制字符输入(ASCII 码) 前两天刚看书看到的,来这里跟大家分享一下有关C#处理指令的问题
C#泛型之泛型委托
skylai · 2006-11-17 · via 博客园 - skylai

在看泛型委托之前还需要先了解委托的概念。
这里讲的委托有两种类型一种是有返回值的,另一种是事件委托。

    //定义有返回值的委托 
    public delegate string GenricDelegate<T, S>(T title, S author);

    
//定义事件委托。
    public delegate void GenricDelegateEnent<E,P>(E Name,P Address);

    
public class GenericDelegateClass<V,F>
    
{
        
//声明委托
        public GenricDelegate<V, F> GdeleValue;
        
//声明事件委托
        public event GenricDelegateEnent<V, F> GdEvent = null;

        
public string GetValues(V title, F author)
        
{
            
//调用委托
            return GdeleValue(title, author);
        }


        
public GenericDelegateClass()
        
{
        }


        
public void InvokeEvent(V name, F address)
        
{
            
if (GdEvent != null)
            
{
                
//调用委托
                GdEvent(name, address);
            }

        }

    }

上面我们定义及调用了泛型委托,接下来就来梆定委托。

        private void btnDelegate_Click(object sender, EventArgs e)
        
{

            GenericDelegateClass
<stringstring> gd = new GenericDelegateClass<stringstring>();
            
//将DelegateReturn事件梆定给GdeleValue
            gd.GdeleValue = new GenricDelegate<stringstring>(DelegateReturn);
            
//将GenericEvent事件梆定给GdEvent
            gd.GdEvent += new GenricDelegateEnent<stringstring>(GenericEvent<string,string>);
        }


        
public string DelegateReturn<T,S>(T title,S author)
        
{
            
return title.ToString() + author;
        }


        
private void GenericEvent<V, F>(V name, F address)
        
{
            
//
        }

在这里我们看到我在梆定DelegateReturn的时候并没有带泛型参数。在这里的泛型参数其实是没什么意义的。因为他的类型取决于调用委托的方法的类型。也就是在前面那段代码中InvokeEvent方法的类型,这里的DelegateReturn要用泛型方法是可以随时跟InvokeEvent的参数类型保持一至。这样梆定后我们再来调用gd.GetValues("my generic post","fastyou");这样调用的其实就是DelegateReturn的方法,这就是委托的好处了,同样调用gd.InvokeEvent("my generic post","fastyou");就是GenericEvent方法。