如何在 C# 中调度事件

发布于 2024-08-25 08:59:49 字数 86 浏览 4 评论 0原文

我希望创建自己的事件并调度它们。 我以前从未在 C# 中这样做过,只在 Flex 中这样做过。我想一定有很多差异。

谁能给我一个很好的例子吗?

I wish to create own events and dispatch them.
I never done this before in C#, only in Flex.. I guess there must be a lot of differencies.

Can anyone provide me a good example?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦魇绽荼蘼 2024-09-01 08:59:49

所有库类中都使用一种模式。也建议您自己的类使用它,尤其是框架/库代码。但当你偏离或跳过几步时,没有人会阻止你。

下面是基于最简单的事件委托 System.Eventhandler 的原理图。

// The delegate type. This one is already defined in the library, in the System namespace
// the `void (object, EventArgs)` signature is also the recommended pattern
public delegate void Eventhandler(object sender, Eventargs args);  

// your publishing class
class Foo  
{
    public event EventHandler Changed;    // the Event

    protected virtual void OnChanged()    // the Trigger method, called to raise the event
    {
        // make a copy to be more thread-safe
        EventHandler handler = Changed;   

        if (handler != null)
        {
            // invoke the subscribed event-handler(s)
            handler(this, EventArgs.Empty);  
        }
    }

    // an example of raising the event
    void SomeMethod()
    {
       if (...)        // on some condition
         OnChanged();  // raise the event
    }
}

以及如何使用它:

// your subscribing class
class Bar
{       
    public Bar()
    {
        Foo f = new Foo();
        f.Changed += Foo_Changed;    // Subscribe, using the short notation
    }

    // the handler must conform to the signature
    void Foo_Changed(object sender, EventArgs args)  // the Handler (reacts)
    {
        // the things Bar has to do when Foo changes
    }
}

当您有信息要传递时:

class MyEventArgs : EventArgs    // guideline: derive from EventArgs
{
    public string Info { get; set; }
}

class Foo  
{
    public event EventHandler<MyEventArgs> Changed;    // the Event
    ...
    protected virtual void OnChanged(string info)      // the Trigger
    {
        EventHandler handler = Changed;   // make a copy to be more thread-safe
        if (handler != null)
        {
           var args = new MyEventArgs(){Info = info};  // this part will vary
           handler(this, args);  
        }
    }
}

class Bar
{       
   void Foo_Changed(object sender, MyEventArgs args)  // the Handler
   {
       string s = args.Info;
       ...
   }
}

更新

从 C# 6 开始,“触发器”方法中的调用代码变得更加容易,可以使用 null 条件运算符 缩短 null 测试?. 无需制作副本,同时保持线程安全:

protected virtual void OnChanged(string info)   // the Trigger
{
    var args = new MyEventArgs{Info = info};    // this part will vary
    Changed?.Invoke(this, args);
}

There is a pattern that is used in all library classes. It is recommended for your own classes too, especially for framework/library code. But nobody will stop you when you deviate or skip a few steps.

Here is a schematic based on the simplest event-delegate, System.Eventhandler.

// The delegate type. This one is already defined in the library, in the System namespace
// the `void (object, EventArgs)` signature is also the recommended pattern
public delegate void Eventhandler(object sender, Eventargs args);  

// your publishing class
class Foo  
{
    public event EventHandler Changed;    // the Event

    protected virtual void OnChanged()    // the Trigger method, called to raise the event
    {
        // make a copy to be more thread-safe
        EventHandler handler = Changed;   

        if (handler != null)
        {
            // invoke the subscribed event-handler(s)
            handler(this, EventArgs.Empty);  
        }
    }

    // an example of raising the event
    void SomeMethod()
    {
       if (...)        // on some condition
         OnChanged();  // raise the event
    }
}

And how to use it:

// your subscribing class
class Bar
{       
    public Bar()
    {
        Foo f = new Foo();
        f.Changed += Foo_Changed;    // Subscribe, using the short notation
    }

    // the handler must conform to the signature
    void Foo_Changed(object sender, EventArgs args)  // the Handler (reacts)
    {
        // the things Bar has to do when Foo changes
    }
}

And when you have information to pass along:

class MyEventArgs : EventArgs    // guideline: derive from EventArgs
{
    public string Info { get; set; }
}

class Foo  
{
    public event EventHandler<MyEventArgs> Changed;    // the Event
    ...
    protected virtual void OnChanged(string info)      // the Trigger
    {
        EventHandler handler = Changed;   // make a copy to be more thread-safe
        if (handler != null)
        {
           var args = new MyEventArgs(){Info = info};  // this part will vary
           handler(this, args);  
        }
    }
}

class Bar
{       
   void Foo_Changed(object sender, MyEventArgs args)  // the Handler
   {
       string s = args.Info;
       ...
   }
}

Update

Starting with C# 6 the calling code in the 'Trigger' method has become a lot easier, the null test can be shortened with the null-conditional operator ?. without making a copy while keeping thread-safety:

protected virtual void OnChanged(string info)   // the Trigger
{
    var args = new MyEventArgs{Info = info};    // this part will vary
    Changed?.Invoke(this, args);
}
难得心□动 2024-09-01 08:59:49

C# 中的事件使用委托。

public static event EventHandler<EventArgs> myEvent;

static void Main()
{
   //add method to be called
   myEvent += Handler;

   //call all methods that have been added to the event
   myEvent(this, EventArgs.Empty);
}

static void Handler(object sender, EventArgs args)
{
  Console.WriteLine("Event Handled!");
}

Events in C# use delegates.

public static event EventHandler<EventArgs> myEvent;

static void Main()
{
   //add method to be called
   myEvent += Handler;

   //call all methods that have been added to the event
   myEvent(this, EventArgs.Empty);
}

static void Handler(object sender, EventArgs args)
{
  Console.WriteLine("Event Handled!");
}
浴红衣 2024-09-01 08:59:49

使用典型的 .NET 事件模式,并假设您的事件中不需要任何特殊参数。您的典型事件和调度模式如下所示。

public class MyClassWithEvents
    {
        public event EventHandler MyEvent;

        protected void OnMyEvent(object sender, EventArgs eventArgs)
        {
            if (MyEvent != null)
            {
                MyEvent(sender, eventArgs);
            }
        }

        public void TriggerMyEvent()
        {
            OnMyEvent(sender, eventArgs);
        }
    }

将某些内容绑定到事件中可以非常简单:

public class Program
{
    public static void Main(string[] args)
    {
        MyClassWithEvents obj = new MyClassWithEvents();

        obj.MyEvent += obj_myEvent;
    }

    private static void obj_myEvent(object sender, EventArgs e)
    {
        //Code called when my event is dispatched.
    }
}

查看 上的链接此 MSDN 页面

Using the typical .NET event pattern, and assuming you don't need any special arguments in your event. Your typical event and dispatch pattern looks like this.

public class MyClassWithEvents
    {
        public event EventHandler MyEvent;

        protected void OnMyEvent(object sender, EventArgs eventArgs)
        {
            if (MyEvent != null)
            {
                MyEvent(sender, eventArgs);
            }
        }

        public void TriggerMyEvent()
        {
            OnMyEvent(sender, eventArgs);
        }
    }

Tying something into the event can be as simple as:

public class Program
{
    public static void Main(string[] args)
    {
        MyClassWithEvents obj = new MyClassWithEvents();

        obj.MyEvent += obj_myEvent;
    }

    private static void obj_myEvent(object sender, EventArgs e)
    {
        //Code called when my event is dispatched.
    }
}

Take a look at the links on this MSDN page

烟柳画桥 2024-09-01 08:59:49

查看'委托'。

  • 定义委托
  • 使用委托类型作为字段/属性(添加“Event”关键字)
  • 您现在公开用户可以使用“+= MyEventMethod;”挂钩的事件

希望这有帮助,

Look into 'delegates'.

  • Define a delegate
  • Use the delegate type as field/property (adding the 'Event' keyword)
  • You are now exposing events that users can hook into with "+= MyEventMethod;"

Hope this helps,

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文