Retrieving property type from CodeProperty in T4 template
Asked Answered
C

1

6

I'm implementing some fairly straight forward code generation using T4, but I'm stuck on a basic problem when it comes to the details of Property generation. When I access the Type property on the CodeProperty objects I want to generate, they are returning 'System.__ComObject' instead of the actual type of the property.

I'm using EnvDTE to find all classes in the project that include my custom attribute. I'm using this to mark certain classes for code generation. So far so good. I'm then stepping over all the CodeElement objects that are the Children of my class. I can find all the properties, it's just I can't get the 'Type' of them.

Here's a snippet of my T4:

public class <#= cls.Name #>_DTO
{
<#
    foreach (CodeElement child in cls.Children)
    {
        if (child.Kind == vsCMElement.vsCMElementProperty)
        {
            var prop = child as CodeProperty;
#>

    public <#= prop.Type.ToString() + " " + child.Name #> { get; set; }

<#
    }
  }
}
#>

And a sample of the output is:

public class TestResult_DTO
{
    public System.__ComObject TestType { get; set; }
}

As you can see, I'm close to valid output, it's just the Type of the property that I'm struggling to access.

Croat answered 3/3, 2014 at 7:16 Comment(0)
B
8

Looking at the docs, I suspect you want AsString instead of ToString(). That would call CodeTypeRef.AsString:

AsString return a string representation for the CodeTypeRef in the language being modeled. For example, if the vsCMTypeRef type is vsCMTypeRefInt, then the string would be "Int" for Visual C# and "Long" for Visual Basic.

I've never written this sort of code myself so I'm just going by the documentation, but it's worth a try :)

Bakerman answered 3/3, 2014 at 7:23 Comment(2)
Did the trick :) EnvDTE is obviously a useful tool, it opens up great stuff, but it's not the most intuitive library to jump in to.Croat
Helped me too! A tiny note : AsString is a property rather than a method.Harvin

© 2022 - 2024 — McMap. All rights reserved.