c# - 从 CodeAttribute 中的参数获取 CodeClass?

标签 c# code-generation t4

我正在处理一些 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 的代码类(它可以在解决方案中的另一个程序集内)?

最佳答案

根据 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/

相关文章:

python - 如何从 BNF 生成随机程序

c# - T4 生成的代码需要访问不同的命名空间/项目

c# - 内存不足的图片框

c# - VS 2013 SDK : How to add a line separator in a CommandBarPopup menu?

c# - Protobuf-net 在序列化期间跳过数据

java - 如何创建一个 bytebuddy 代理来拦截带注释字段的字段 setter ?

java - 编辑 "Test for Existing Class"的 Netbeans 模板

visual-studio-2010 - T4 "Compiling transformation: An assembly with the same identity ' ' has already been imported. Try removing one of the duplicate references."?

visual-studio - 从 Entity Framework 数据库优先切换到代码优先

c# - 序列化包含字典的对象,以便字典键/值呈现为包含对象的一部分