c# - EnvDTE 从 CodeElement 中检索数据类型

标签 c# envdte

我正在使用 EnvDTE 在我的最新项目中生成一些代码。

我有一个给定 C# 类的代码类对象的引用,但现在我想遍历它的所有成员(在 codeClass.Members 中)并检查它们的类型。

但是,我无法从循环遍历 codeClass.Members 时获得的 CodeElement 对象中检索给定成员的类型。

如何检索类型(int、string 等)?

PS:反射不是我的用例的选项。

最佳答案

CodeElement 具有 Members 属性,它是 CodeElement 的集合。 CodeElement 有一个 Kind 属性,从中你可以知道我们在谈论什么样的成员。然后您可以将每个成员强制转换到适当的界面并环顾四周。大多数子类都有一个 Type 属性,其中包含您要查找的信息。

我在宏编辑器的一个模块中输入了这个:

Public Sub DisplayStuff()

    Dim objTextSel As TextSelection
    Dim objCodeCls As CodeClass
    objTextSel = CType(DTE.ActiveDocument.Selection, TextSelection)
    objCodeCls = CType(objTextSel.ActivePoint.CodeElement(vsCMElement.vsCMElementClass), CodeClass)

    If objCodeCls Is Nothing Then
        MsgBox("Please launch this macro when the cursor is within a class")
        Exit Sub
    End If

    For Each elt As CodeElement2 In objCodeCls.Members

        Select Case elt.Kind

            Case vsCMElement.vsCMElementVariable

                Dim v As CodeVariable2 = CType(elt, CodeVariable2)

                MsgBox(v.Name & " is a variable of type " & v.Type.AsString)

            Case vsCMElement.vsCMElementProperty

                Dim p As CodeProperty2 = CType(elt, CodeProperty2)

                MsgBox(p.Name & " is of type " & p.Type.AsString)
        End Select


    Next
End Sub

它只获取编辑器中光标所在位置的类,并显示任何字段或属性的类型信息。

关于c# - EnvDTE 从 CodeElement 中检索数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2969573/

相关文章:

c# - DataGridView 在更改 Checkbox 值后直接更新数据源

c# - 无法将 DTE、项目或解决方案转换为 VCProject 和 VCCodeModel

visual-studio-2010 - Visual Studio 扩展 : Wait for all projects to complete loading with IVsSolutionEvents OnAfterOpenSolution

visual-studio - 使用自定义加载项更改 Visual Studio 颜色的性能

c# - Visual Studio 2012 DTE 将焦点更改为新的解决方案项

c# - 如何在现有 JSON 字符串中追加节点?

c# - .Net 中 NameValueCollection 的通用形式

c# - 我的字典 wp 应用程序在 c#

c# - 如何使用poco实体生成器

c# - DTE.ExecuteCommand 并等待