来源:http://www.imcoder.org/custom-control/189732.htm
I don't get it... what's the objective of EnsureChildControls method in a CompositeControl class properties? There's no difference if I use it or not!
Public Property Required() As Boolean
Get
EnsureChildControls()
Return _Required
End Get
Set(ByVal value As Boolean)
EnsureChildControls()
_Required = value
End Set
End Property
there's no difference using
Public Property Required() As Boolean
Get
Return _Required
End Get
Set(ByVal value As Boolean)
_Required = value
End Set
End Property
Let me cite you from [1, p.924]
EnsureChildControls makes sure child controls are created prior to accessing them. For example, if you had a property such as the following…
Public Class MySampleControl
Inherits System.Web.UI.WebControls.CompositeControl
' This sample is only meant to show why EnsureChildControls can be necessary.
Protected WithEvents FirstNameTextBox As System.Web.UI.WebControls.TextBox
Public Property FirstName() As String
Get
' Will call CreateChildControls if needed
EnsureChildControls()
Return FirstNameTextBox.Text
End Get
Set(ByVal value As String)
' Will call CreateChildControls if needed
EnsureChildControls()
FirstNameTextBox.Text = value
End Set
End Property
Protected Overrides Sub CreateChildControls()
MyBase.CreateChildControls()
FirstNameTextBox = New System.Web.UI.WebControls.TextBox
FirstNameTextBox.ID = "FirstNameTextBox"
Controls.Add(FirstNameTextBox)
End Sub
End Class
' Some page/user control class...
Public Sub CreateSampleControl()
Dim ctl As New MySampleControl()
' EnsureChildControls makes sure the property will
' not fail when accessed before default call to CreateChildControls
ctl.FirstName = "Brian"
Controls.Add(ctl)
End Sub
Yet Microsoft's own post on the topic indicates that if you are using the new CompositeControl in ASP.NET 2.0 you no longer have to explicitly call EnsureChildControls():
The CompositeControl class is new in ASP.NET 2.0. If you created custom controls in ASP.NET version 1.0 or 1.1, you had to implement the INamingContainer interface to create a new naming scope for child controls. In addition, you had to override the Controls property and invoke the EnsureChildControls method. In ASP.NET 2.0, these and other steps are performed by the CompositeControl class.