Getting the CodeClass from argument inside CodeAttribute?

青春壹個敷衍的年華 提交于 2019-12-10 19:26:58

问题


I am working on some T4 code generation, for this I need the CodeClass of the type that is passed inside the constructor of BarAttribute.

class Baz { }
class Bar : Attribute { public Bar (Type type) {    } }

[Bar(typeof(Baz))]
public class Foo
{
}

This is what I have so far inside my T4 Template, I just give the CodeAttribute '[Bar(typeof(Baz))]' to the function:

private CodeClass GetType(CodeElement codeElement)
{
    CodeAttribute attribute = (CodeAttribute)codeElement;
    if (attribute.Name == "Bar")
    {
        foreach (CodeElement child in attribute.Children)
        {
            EnvDTE80.CodeAttributeArgument attributeArg = (EnvDTE80.CodeAttributeArgument)child;
            WriteLine(attributeArg.Value);
        }
    }

    return null;
}

The function now will just write: typeof(Baz), how can I get the CodeClass of Baz (which can be inside another assembly within the solution) without iterating thru all Projects, ProjectItems, CodeElements, etc?


回答1:


As per William's reply, you are limited to the design-time information, which will be the unparsed text passed to the attribute. If you are interested in finding the CodeClass referenced in the typeof keyword without resorting to recursion, you can use the VisualStudioAutomationHelper class found in tangible's T4 Editor template gallery. You use it like this:

var project = VisualStudioHelper.CurrentProject;

var allClasses = VisualStudioHelper.GetAllCodeElementsOfType(project.CodeModel.CodeElements, EnvDTE.vsCMElement.vsCMElementClass, false);

allClasses.Cast<EnvDTE.CodeClass>().Single(x => x.Name == searchedClassName);


来源:https://stackoverflow.com/questions/6430535/getting-the-codeclass-from-argument-inside-codeattribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!