首页 新闻 赞助 找找看

c#真高手进。。语法难题

0
悬赏园豆:5 [已关闭问题] 关闭于 2013-02-24 22:15

       private EventHandler u;


        public event EventHandler U
        {
            add
            {
                 }
            remove
            {
                            }
        }

这段代码什么意思??????????

彬彬@科比的主页 彬彬@科比 | 初学一级 | 园豆:43
提问于:2013-02-24 00:21
< >
分享
所有回答(1)
0

我看这是一个语法错误的例子,看代码的本意应该是在添加事件处理程序时,如果有遇到同样的处理程序,则只添加一次。但代码有误。(会死循环)

陈希章 | 园豆:2538 (老鸟四级) | 2013-02-24 11:14

那要怎么改呀??

支持(0) 反对(0) 彬彬@科比 | 园豆:43 (初学一级) | 2013-02-24 13:38

@彬彬@科比: 

 

下面是一个例子

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

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{


var c = new MyClass();
c.U += c_U;
c.U += c_U;

c.RaiseEvent();

Console.Read();
}

static void c_U(object sender, EventArgs e)
{
Console.WriteLine("hello,world");
}
}

class MyClass
{
private EventHandler u;
/// <summary>
/// 一个自定义事件
/// </summary>
public event EventHandler U
{
add
{
//如果用户注册的事件处理程序是同一个,则只注册一次
if (u == null || !u.GetInvocationList().Contains(value))
u = (EventHandler)Delegate.Combine(u, value);
}
remove
{
//检查以便避免无效地删除
if (u != null && u.GetInvocationList().Contains(value))
u = (EventHandler)Delegate.Remove(u, value);
}
}

/// <summary>
/// 触发事件的代码
/// </summary>
public void RaiseEvent()
{
if (u != null) u(this, null);
}
}
}

支持(0) 反对(0) 陈希章 | 园豆:2538 (老鸟四级) | 2013-02-24 19:42
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册