问题
This is just for a better understanding of the ASP.NET framework. When you use a control in a declarative way (that would be web form markup), you assign event handlers by their method name using an attribute that starts with On
:
<asp:Button runat="server" OnClick="..."/>
But when you look at the System.Web.UI.WebControls.Button class it has an EventHandler property named Click
that the delegate is assigned to:
button.Click += new EventHandler(...);
So how is this implemented? Is that just a convention followed by the parser?
I know, it's a strange question, the answer will do nothing but satisfy my curiosity.
回答1:
This is a naming convention used by ASP.NET which, rather unhelpfully, looks identical to another common naming convention widely used throughout .NET. Despite the apparent similarity, these two conventions are unrelated.
The .NET-wide convention, which turns out to be irrelevant here, is that it's common for events to have corresponding methods that raise the event, and for those methods' names to be formed by adding an On
prefix to the event name. For example, the Click
event offered by Button
is related to an OnClick
method, which raises that event (as has already been stated in another answer here).
The confusing part is that the OnClick
method has nothing to do with the OnClick
attribute that the question concerns.
It's easy to demonstrate that the OnSomeEvent
methods are irrelevant here by writing a control that doesn't have any such method. Here's the codebehind for a simple user control:
public partial class EventWithoutMethod : System.Web.UI.UserControl
{
public event EventHandler Foobar;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Foobar != null)
{
Foobar(this, EventArgs.Empty);
}
}
}
This declares a Foobar
event. (It never actually raises it, but that doesn't matter for the purposes of exploration.) It does not define an OnFoobar
method. Nevertheless, ASP.NET is perfectly happy for us to use the OnSomeEvent
convention when we use the control:
<user:EventWithoutMethod runat="server" OnFoobar="FooHandler" />
In fact, it's not only happy for us to do that, it actually requires it. Even though my control doesn't define any member called OnFoobar
—the event is called just Foobar
—I have to write OnFoobar
if I want to attach the event handler from my .aspx
file. If I just put a Foobar
attribute in there in an attempt to attach the event, the handler will never run. (Unhelpfully, ASP.NET doesn't generate an error when you do that, it just silently fails to do anything with the attribute, and the event handler never runs.)
来源:https://stackoverflow.com/questions/969128/how-come-the-attributes-for-event-handler-properties-on-asp-net-controls-have-a