尽管定义了事件,但为什么我的类没有实现该接口?

问题描述 投票:0回答:1

我目前正在了解具有以下代码的事件:

public interface INotifyMessageChanged
{
    public event EventHandler MessageChanged;
}

public class Academy : Organization, INotifyMessageChanged
{
    public event EventHandler? NotifySubScriber;

    private string message = "";
    public string Message
    {
        get { return message; }
        set { message = value; MessageChanged(); }
    }
    public Academy(string name, string address) : base(name)
    {
        Address = address;
    }

    void MessageChanged()
    {
        NotifySubScriber?.Invoke(this, nul);
    }
}

代码产生以下错误:

CS0535  'Academy' does not implement interface member 'INotifyMessageChanged.MessageChanged'

接口中的MessageChanged事件不应该和类中的事件一一对应吗?

c# events delegates
1个回答
0
投票

您的活动签名不同:

EventHandler MessageChanged
EventHandler? NotifySubscriber

public interface INotifyMessageChanged
{
    public event EventHandler MessageChanged;
}

public class Academy : Organization, INotifyMessageChanged
{
    public event EventHandler MessageChanged;

    private string message = "";
    public string Message
    {
        get { return message; }
        set { message = value; this.OnMessageChanged(); }
    }
    public Academy(string name, string address) : base(name)
    {
        Address = address;
    }

    void OnMessageChanged()
    {
        this.MessageChanged?.Invoke(this, null);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.