我正在处理一些 T4 代码生成,为此我需要在 BarAttribute 的构造函数中传递的类型的 CodeClass。

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

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

这是迄今为止我在 T4 模板中所拥有的,我只是将 CodeAttribute '[Bar(typeof(Baz))]' 提供给函数:
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;
}

该函数现在将只写:typeof(Baz),如何在不遍历所有项目、项目项、代码元素等的情况下获取 Baz 的 CodeClass(可以在解决方案中的另一个程序集中)?

最佳答案

根据 William 的回复,您仅限于设计时信息,这将是传递给属性的未解析文本。如果您有兴趣在不求助于递归的情况下查找 typeof 关键字中引用的 CodeClass,您可以使用 tangible's T4 Editor 模板库中的 VisualStudioAutomationHelper 类。你像这样使用它:

var project = VisualStudioHelper.CurrentProject;

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

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

关于c# - 从 CodeAttribute 中的参数获取 CodeClass?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6430535/

10-13 22:56