EventArgs.Empty clarification?

旧街凉风 提交于 2020-01-02 09:29:13

问题


I have a method

protected void Item_Click(object sender, EventArgs e)
{     }

I wanted that other code to call this method. ( didn't really need the sender nor e)

something like :

Item_Click(null, null)

But then I remembered I can use EventArgs.Empty instead.

Mouse hovering over it shows :

Wait...What ?

EventArgs.Empty represents an event ? it is not. it should represent empty argument not an event.

just like string.empty represent empty string.

  • Am I missing something here?

回答1:


It's just poor documentation, conflating two concepts in one word. The latest documentation seems a little better:

Provides a value to use with events that do not have event data.

The trouble is that "an event" has two separate meanings:

  • The event that you can subscribe to
  • A single "instance" of that event being raised

For example, it wouldn't be unreasonable to say: "Subscribe to the KeyPress event to receive keyboard-related events."

(The word "delegate" is just as bad, used to describe delegate types and instances of them.)

It's all unfortunate, but rest assured that you have the right idea.

As an aside, if you want to call the method other than when the event is raised, I'd potentially separate it into two methods:

// This only exists to handle the event, delegating to the DoSomething method
private void HandleItemClicked(object sender, EventArgs e)
{
    DoSomething();
}

// This can be called from other code, and should be named according to what it
// does.
private void DoSomething()
{
}

If you're subscribing to the event manually, you don't even need the extra method:

item.Click += delegate { DoSomething(); };

This way you make it clear that your "real" method doesn't care about the sender or event args, and you don't need to provide "dummy" values when calling it.



来源:https://stackoverflow.com/questions/16333971/eventargs-empty-clarification

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!