如果存在,如何获取控件的 TagName?

How to get TagName of Control if exists?

我写过这段代码:

    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

如果AlohaEnabledTrue,那么我打算在head标签中添加一些链接和脚本。事先不知道会用到什么样的Master,所以我迭代它的Controls,通过反射寻找一个叫TagName的字段。如果 field 有一个值,那么我将它与 "head" 进行比较,如果匹配,那么我打算添加 aloha scripts (虽然这个问题更笼统,我可能需要这也适用于不同的脚本或其他地方)。 TagNameSystem.Web.UI.HtmlControls.HtmlControl 的字段。我的测试用例中的第 0 个 control returns

{Name = "HtmlHead" FullName = "System.Web.UI.HtmlControls.HtmlHead"}

control.GetType。如果我们看 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 TagNamePublic,我会期望 control.GetType.GetField("TagName")Return "head"。取而代之的是 returns Nothing。我想知道这种行为的原因是什么?

编辑:

FloatingKiwi是对的,问题是我在搜索一个字段,但这是一个属性,所以我没有找到它(什么是无论如何,我们可以用方法解决它们的任务)。在此期间我使用了变通方法:

        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

我想知道哪个是更好的解决方案:我的变通方法,还是 属性 使用反射搜索?

这是一个 属性 而不是字段。使用

Dim propInfo = control.GetType.GetProperty("TagName") 代替。

这将 return 一个 属性Info 对象。要获得实际值,请使用

Dim result = propInfo .GetValue(control, Nothing)