开发者

EnvDTE Retrieving the data type from a CodeElement

开发者 https://www.devze.com 2023-01-02 18:17 出处:网络
I am using EnvDTE to generate some code in my latest project. I have a reference to a CodeClass-Object for a given C#-Class but now I wanted to loop through all of its members (in codeClass.Members)

I am using EnvDTE to generate some code in my latest project.

I have a reference to a CodeClass-Object for a given C#-Class but now I wanted to loop through all of its members (in codeClass.Members) and check their types.

However I can't manage to retrieve the type of the given member from the CodeElement-开发者_Go百科Object that I get when looping through codeClass.Members.

How can I retrieve the type (int, string etc.)?

PS: Reflection is not an option for my usecase.


CodeElement has the Members property, which is a collection of CodeElement. CodeElement has a Kind property, from which you can know what kind of member we're talking about. Then you can cast each member to the appropriate interface and have a look around. Most subclasses have a Type property, with the info you are looking for.

I typed this in the Macro editor, in a module:

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

It simply takes the class that is where the cursor is in the editor and displays the type info for any field or property.

0

精彩评论

暂无评论...
验证码 换一张
取 消