无法获取.net类中已声明方法的列表

时间:2019-04-15 23:36:29

标签: vb.net reflection

已经阅读了很多有关使用反射来获取给定类中方法列表的文章,但是我仍然很难获得该列表,并且需要寻求​​帮助。这是我当前的代码:

Function GetClassMethods(ByVal theType As Type) As List(Of String)
    Dim methodNames As New List(Of String)
    For Each method In theType.GetMethods()
        methodNames.Add(method.Name)
    Next
    Return methodNames
End Function

我这样称呼这个方法:

GetClassMethods(GetType(HomeController))

返回有43个方法,但是我只想要我在类中编写的方法。下图显示了返回内容的开头。我声明的方法在此列表中,但位于位置31-37。实际上有9个声明的方法,但是此列表未显示Private方法。

enter image description here

当我看着theType时,看到了我想要的属性。 DeclaredMethods显示了每个已声明的方法,公共方法和私有方法。

enter image description here

但是,我无法使用这样的语句访问此属性。

Dim methodList = theType.DeclaredMethods

返回的错误是DelaredMethods不是Type的成员。所以,我的问题是多个:

1)最重要的是,我需要什么代码来检索该类中每个已声明的方法,并且仅检索我声明的方法?

2)为什么我无法访问提供DeclaredMethods()列表的属性?

1 个答案:

答案 0 :(得分:3)

尝试一下:

Function GetClassMethods(ByVal theType As Type) As List(Of String)
    Dim flags = Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.DeclaredOnly
    Dim result = theType.GetMethods(flags).
          Where(Function(m)  Not m.IsSpecialName).
          Select(Function(m) m.Name)
    Return result.ToList()
End Function

或使用泛型获得一些乐趣:

Function GetClassMethods(Of T)() As List(Of String)
    Dim flags = Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.DeclaredOnly
    Dim result = GetType(T).GetMethods(flags).
          Where(Function(m)  Not m.IsSpecialName).
          Select(Function(m) m.Name)
    Return result.ToList()
End Function

IsSpecialName过滤器不包括具有编译器生成名称的方法,例如编译器用来实现属性的特殊方法。如果还需要包括NonPublic成员,则还可以使用这些标志来发挥作用。


最后,只要您有一个以Return something.ToList()结尾的方法(或者可能以它结尾,如我的适应证所示),更改该方法以返回{{1} } ,并在真正需要时让调用代码调用IEnumerable(Of T)。所以我上面的第一个例子确实更好:

ToList()

嘿,那可能是单线。然后,对于确实需要列表的情况,可以执行以下操作:

Function GetClassMethods(ByVal theType As Type) As IEnumerable(Of String)
    Dim flags = Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.DeclaredOnly
    Return theType.GetMethods(flags).
          Where(Function(m)  Not m.IsSpecialName).
          Select(Function(m) m.Name)
End Function

在许多情况下,您将发现根本不需要使用Dim methodNames As List(Of String) = GetClassMethods(HomeController).ToList() ;通用ToList()足够好。在仅通过IEnumerable循环使用结果的任何地方,这都是正确的。现在,程序中的内存使用突然减少了。

相关问题