1

我需要一点帮助......我刚刚开始使用 C#,当布尔值发生变化时我需要引发一个事件。我有一堂课:

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

    }
}

但是当 _isconnected 更改值时如何引发/触发事件?

4

2 回答 2

2

它应该很简单

    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
于 2013-10-01T12:34:24.470 回答
1

你有所有的代码,你只需要触发器......

public void Disconnect()
{
    _isconnected = false;
    OnDisconnected();
}
于 2013-10-01T12:31:12.557 回答