簡體   English   中英

為什么 EventArgs 構造函數不受保護?

[英]Why is the EventArgs constructor not protected?

我想知道為什么EventArgs構造函數不受保護,因為為每個事件分配一個空的 object 資源似乎是浪費(盡管很小),尤其是當有一個 singleton EventArgs.Empty顯然使用起來更有效時。 這讓我感到驚訝,特別是當 .NET 的其他部分確實有一個受保護/私有構造函數來避免多次不必要的分配時,例如Comparer<T>

在任何情況下,創建一個new EventArgs() (不是子類)實際上是有意義的,或者構造函數是否僅可用於簡化沒有經驗的開發人員的使用?

我會說這是因為EventArgs class 的ComVisible屬性設置為true

以下FxCop 規則支持這一點:

特別標記為對 COM 可見的引用類型包含公共參數化構造函數,但不包含公共默認(無參數)構造函數。

一個更大的問題是“為什么總是使用 EventArgs,即使您的事件不需要任何信息?”。 如果 EventArgs 沒有公共構造函數,您將無法執行此操作。

一個很好的優勢是,如果將來您確實想傳遞信息,任何現有代碼仍然可以編譯。 例如,下面的 class 一開始只使用 EventArgs,但現在傳遞了一個包含一些“有用信息”的字符串。

class SomeEventSource
{
    public event EventHandler<SomeEventArgs> MyEvent;

    public void FireTheEvent()
    {
        MyEvent(this, new SomeEventArgs("This information is interesting"));
    }
}

class SomeEventArgs : EventArgs
{
    public SomeEventArgs(string interestingInformation)
    {
        InterestingInformation = interestingInformation;
    }
    public string InterestingInformation { get; private set; }
}

此客戶端代碼是在更改之前編寫的,但它仍然可以編譯。 如果原始版本沒有使用 EventArgs,那么更改的實施成本會更高。

class SomeClient
{
    private readonly SomeEventSource _source;

    public SomeClient()
    {
        _source = new SomeEventSource();
        _source.MyEvent += source_MyEvent;
    }

    public void RunTest()
    {
        _source.FireTheEvent();
    }

    void source_MyEvent(object sender, EventArgs e)
    {
        // Do something
    }
}

EventArg 的構造函數上有一個注釋,可以在某些情況下對其進行優化。 EventArgs 本身被標記為 Serializable 和 ComVisible。 您創建的任何子類都將利用這些優勢並適應模式。

暫無
暫無

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

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