C# 调用一个事件

标签 c# events event-handling

<分区>

我在这里创建了这个程序来演示我正在尝试做的事情。您可以看到,除了应调用 _OnSell 事件的那行代码外,所有代码都已编写。 (第 21 行~)

using System;

namespace example
{
    public class Car
    {
        public int Price;
        public string ModelName;
        private Boolean Sold;
        public delegate void SellEventHandler(string str);
        public event SellEventHandler _OnSell;
        public Boolean _Sold
        {
            get { return Sold; }
            set
            {
                Sold = value;
                if (Sold == true)
                {
                    // INVOKE _OnSell EVENT HERE !!
                }
            }
        }

        public void OnSell(string str)
        {
            Console.WriteLine("library stuff");
        }

        public Car(int price, string modelname)
        {
            Price = price;
            ModelName = modelname;
            Sold = false;
            _OnSell = OnSell;
        }
    }

    public class Program
    {
        static void Main()
        {
            Program p1 = new Program();
            Car _car = new Car(6000, "audi");
            _car._OnSell += p1.Car_OnSell;
            _car._Sold = Console.ReadLine() == "true" ? true : false;
            Console.ReadLine();
        }

        public void Car_OnSell(string message)
        {
            Console.WriteLine("user stuff");
        }
    }
}

每当值 _car._Sold 更改时,我都试图调用事件 _car._OnSell。我如何在 C# 中做到这一点?

最佳答案

参见 Handling and Raising Events

因此,按照提供的示例,代码将如下所示。

请注意更清洁的公共(public) API 的名称更改以及事实上的一致性和命名标准。

public class Car
{
    // Note use of `sender` convention
    public delegate void SoldEventHandler(object sender, string str);

    // Events normally do not have the `On` prefix, also the event
    // name is normally the sense-correct verb such as `Sold` or `Selling`.
    public event SoldEventHandler Sold;

    private bool _isSold;
    public bool IsSold
    {
        get { return _isSold; }
        set
        {
            if (value && !_isSold) {
               // Only sell when false -> true
               OnSold("whatever string it is supposed to be");
            }
            _isSold = value;
        }
    }

    // "Typically, to raise an event, you add a method that is marked as protected and virtual.
    //  .. Name this method OnEventName; for example, OnDataReceived."
    public virtual void OnSold(string str)
    {
        // Follow the conventions in the link - ask on SO as to why the local
        // variable and check for null are important/necessary.
        var handler = Sold;
        if (handler != null) {
            handler(this, str);
        }
    }

// ..

    _car.Sold += p1.Car_OnSell;
    _car.IsSold += Console.ReadLine() == "true" ? true : false;

在大多数情况下,我建议让事件采用 (object sender, EventArgs args),因为它使事件的 future 更改更加灵活 - 这讨论在链接中。

关于C# 调用一个事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27220084/

相关文章:

c# - GUI 事件是否有可能中断 GUI 线程的运行代码以执行其自己的事件处理程序方法?

java - 如何将事件数据和事件名称从 Spring Boot 发送到 Angular?

javascript - jQuery 取消先前排队的事件处理程序以重新启动 CSS 动画

c# - 在编写单元测试时断言 "nothing happened"

events - JavaFX 2.2 : Hooking Slider Drag n Drop Events

c# - INotifyPropertyChanged 的​​ PropertyChanged 事件处理程序背后是什么?消息接收/处理机制是什么?

javascript - 别处点击事件?

c# - 将事件处理方法设为静态是否存在任何陷阱?

c# - List<T> 与 BindingList<T> 优点/缺点

c# - 无法将 DateTime 从 EF "Code First"保存到 MySQL 远程数据库