I have written this code:
If (AlohaEnabled) Then
Dim head As Control = Nothing
For Each control In Master.Controls
Dim field = control.GetType.GetField("TagName")
If ((field IsNot Nothing) AndAlso (field.GetValue(control).Equals("head"))) Then
'Add aloha scripts
End If
Next
End If
If AlohaEnabled
is True
, then I intend to add some links and scripts to the head
tag. I do not know in advance what kind of Master
will be used, therefore I iterate its Controls
and look for a field called TagName
through reflection. If field
has a value, then I compare it to "head"
and if it is a match, then I intend to add aloha script
s (the question is more general though, I could need this for different scripts as well or somewhere else). TagName
is a field of System.Web.UI.HtmlControls.HtmlControl. The 0'th control
in my test case returns
{Name = "HtmlHead" FullName = "System.Web.UI.HtmlControls.HtmlHead"}
on control.GetType
. If we look at System.Web.UI.HtmlControls.HtmlHead, we see that it inherits System.Web.UI.HtmlControls.HtmlGenericControl, which on its turn inherits System.Web.UI.HtmlControls.HtmlContainerControl, which inherits from HtmlControl
. Since TagName is Public
, I would expect control.GetType.GetField("TagName")
to Return
"head"
. Instead of that, it returns Nothing
. I wonder what is the cause of this behavior?
EDIT:
FloatingKiwi is right, the problem was that I was searching for a field, but this is a property, therefore I did not find it (what is the purpose of properties anyway, we can resolve their tasks with methods). I have used a work-around in the meantime:
For Each control In Master.Controls
If (TypeOf control Is System.Web.UI.HtmlControls.HtmlControl) Then
Dim htmlControl = CType(control, System.Web.UI.HtmlControls.HtmlControl)
If (htmlControl.TagName.Equals("head")) Then
'Add aloha scripts
End If
End If
Next
I wonder which is the superior solution: my work-around, or property searching using reflection?
It's a Property not a Field. Use
Dim propInfo = control.GetType.GetProperty("TagName")
instead.
That will return a PropertyInfo object. To get the actual value use
Dim result = propInfo .GetValue(control, Nothing)