簡體   English   中英

如何從不同的班級引發同一事件?

[英]How to raise the same event from different classes?

我有一個包含許多類的類庫。 這些類中的任何一個都應該能夠在任何時間點向客戶端發送消息(字符串)。 我想要一個可以從多個類中引發的通用事件。 我不希望每個班級都有單獨的活動。

像這樣:

public class GenericEvent
{
    // Here I have an event.   
}

public class LibClass1
{
    //Raise event here.
}

public class LibClass2
{
    //Raise event here
}

public class Client
{
  //Subscribe to the event here
}

這是正確的方法嗎? 如果是,如何實現? 我查找的示例每個類都有一個單獨的事件。

這取決於該事件是什么以及用例,但是選項之一是使用繼承:

public class GenericEvent
{
    // Here I have an event.
    protected void RaiseEvent();
}

public class LibClass1 : GenericEvent 
{
    public voidDoSomethingAndRaiseEvent()
    {
        // ...
        RaiseEvent();
    }
}

通常是這樣實現INotifiPropertyChanged

如果無法進行繼承並且您正在使用聚合,則LibClass1LibClass2應該充當GenericEvent某些外觀/裝飾器:它們必須具有自己的事件,該事件GenericEvent的事件和方法的調用GenericEvent到引發它的方法:

public class GenericEvent
{
    public event EventHandler SomeEvent;
    // ...
}

public class LibClass1
{
    private readonly GenericEvent _ge;

    // ...

    public event EventHandler SomeEvent
    {
        add { _ge.SomeEvent += value; }
        remove { _ge.SomeEvent -= value; }
    }

    public void DoSomethingAndRaiseEvent()
    {
        // ...
        SomeEvent?.Invoke(this, EventArgs.Emtpy);
    }
}
    public class MyEventArgs : EventArgs
    {
        // class members
    }

    public abstract class Lib
    {
        public event EventHandler ShapeChanged;

        public virtual void OnShapeChanged(MyEventArgs e)
        {
            if (ShapeChanged != null)
            {
                ShapeChanged(this, e);
            }
        }
    }

    public class LibClass1 : Lib
    {
        //Raise event here.
    }

    public class LibClass2 : Lib
    {
        //Raise event here
    }

    static void Main(string[] args)
    {
        LibClass1 lib1 = new LibClass1();
        LibClass2 lib2 = new LibClass2();

        lib1.ShapeChanged += Lib1_ShapeChanged;
        lib2.ShapeChanged += Lib1_ShapeChanged;

        lib1.OnShapeChanged(new MyEventArgs());

    }

在這里,完整的示例將創建一個包含事件的抽象類。

我會處理繼承問題。 例如:

public class ParentClass : Form
{
    public ParentClass() {
        this.FormClosed += sendString;
    }

    private void sendString(object sender, FormClosedEventArgs e)
    {
        throw new NotImplementedException();
    }
}

public class GenericEvent : ParentClass { }
public class LibClass1 : ParentClass { }
public class LibClass2 : ParentClass { }
public class Client : ParentClass { }

現在,您所有的Clase都有ParentClass事件。

我有另一種方法。

從一個基類派生所有類。 (當然,.net或MFC或Qt或Java框架都可以這樣做)。

您在基類中只有一個事件“事件1”。 在該event1處理程序中,引發“事件2”。

將所有子類訂閱到父類的“ event2”,並在各個子類中處理您的業務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM