【问题标题】:Read class properties in mvc4 T4 template读取 mvc4 T4 模板中的类属性
【发布时间】:2013-07-05 19:46:21
【问题描述】:

我正在开发一个 T4 模板,该模板将基于核心上的实体生成视图模型。 例如,我在 Core 中有 News 类,我希望这个模板生成这样的视图模型

public class News
{
    public property int Id {get;set;}
    public property string Title {get;set;}
    public property string Content {get;set;}
}

public class NewsCreate
{
    public property int Id {get;set;}
    public property string Title {get;set;}
    public property string Content {get;set;}
}
public class NewsUpdate
{
    public property int Id {get;set;}
    public property string Title {get;set;}
    public property string Content {get;set;}
} 

现在只有这两个。但我找不到获取 News 类属性的方法。 我如何使用反射来获取它们和 . . .

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 t4 scaffolding


    【解决方案1】:

    假设您的“新闻”类与您希望在其中创建视图位于同一个项目中,您有两种可能性:

    1. 构建您的项目,然后使用 T4 模板引用输出程序集 <#@ assembly name="$(TargetPath)" #>。然后你可以在模板中使用标准反射来达到你想要的类。但请注意,您总是反映您的上一个版本可能已过时和/或包含错误!
    2. 看看有形的 T4 编辑器。它是免费的,并为 T4 模板提供语法高亮 + IntelliSense。它还有一个免费的模板库,其中包含一个名为“tangible VisualStudio Automation Helper”的模板。 将这个包含到您的模板中,并使用 Visual Studio 代码模型迭代当前解决方案中的所有类:

      <# var project = VisualStudioHelper.CurrentProject;
      
      // get all class items from the code model
      var allClasses = VisualStudioHelper.GetAllCodeElementsOfType(project.CodeModel.CodeElements, EnvDTE.vsCMElement.vsCMElementClass, false);
      
      // iterate all classes
      foreach(EnvDTE.CodeClass codeClass in allClasses)
      {
          // iterate all properties
          var allProperties = VisualStudioHelper.GetAllCodeElementsOfType(codeClass.Members, EnvDTE.vsCMElement.vsCMElementProperty, true);
          foreach(EnvDTE.CodeProperty property in allProperties)
          {
              // check if it is decorated with an "Input"-Attribute
              if (property.Attributes.OfType<EnvDTE.CodeAttribute>().Any(a => a.FullName == "Input"))
              {
                  ...
              }
          }
      }
      #>
      

    希望有帮助!

    【讨论】:

    • 仅供参考;还有 roslyn 可以用来做 text => 语法树转换。您还可以在 T4 中定义 News 的模型,并从中生成所有变体,避免使用外部工具或反射。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2011-06-25
    相关资源
    最近更新 更多