简体   繁体   English

新手如何在C#中引发/触发事件

[英]Newbie how to raise/trigger events in C#

I need a litle help here.... I'm just getting started with C# and I need to raise an event when a bool value changes. 我需要一个litle帮助....我刚刚开始使用C#,我需要在bool值改变时引发一个事件。 I have a class with this: 我有一个课:

using System;

namespace WOCA
{
    public class Arduino
    {

        public event EventHandler Disconnected;

        **protected virtual void OnDisconnected()
        {
            EventHandler handler = Disconnected;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }**

        private bool _isconnected;
        public bool IsConnected
        {
            get 
            {
                 return _isconnected;
            }
        }

        #region Methods
        public void Connect()
        {
            //TODO implement code to connect
            _isconnected = true;
        }
        public void Disconnect()
        {
            //TODO implement code to connect
            _isconnected = false;

        }

        #endregion Methods

    }
}

But how to I raise/trigger an event when _isconnected changes value? 但是当_isconnected更改值时,如何引发/触发事件?

it should be simple 它应该很简单

    public event EventHandler Disconnected;

    protected virtual void OnDisconnected()
    {
        EventHandler handler = Disconnected;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }

    private bool _isconnected;
    public bool IsConnected
    {
        get
        {
            return _isconnected;
        }
        private set
        {
            if (!value && _isConnected)
            {
                OnDisconnected();
            }
            _isconnected = value;
        }
    }

    #region Methods
    public void Connect()
    {
        //TODO implement code to connect
        IsConnected = true;
    }
    public void Disconnect()
    {
        //TODO implement code to connect
        IsConnected = false;

    }

    #endregion Methods

You have all the code there, you just need the trigger... 你有所有的代码,你只需要触发器......

public void Disconnect()
{
    _isconnected = false;
    OnDisconnected();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM