C# 读取mvc4 T4模板中的类属性

C# 读取mvc4 T4模板中的类属性,c#,asp.net-mvc,asp.net-mvc-4,t4,scaffolding,C#,Asp.net Mvc,Asp.net Mvc 4,T4,Scaffolding,我正在开发一个T4模板,该模板将基于core上的实体生成视图模型。 例如,我在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 {

我正在开发一个T4模板,该模板将基于core上的实体生成视图模型。 例如,我在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类的属性。 我如何使用反射来获取它们和

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

  • 构建项目,然后使用引用T4模板中的输出程序集
    。然后,您可以在模板内使用标准反射来达到所需的类。但是要小心,您总是反映您的上一个版本可能已经过时和/或包含错误
  • 看看有形的T4编辑器。它是免费的,并为T4模板提供语法突出显示+智能感知。它还有一个免费的模板库,其中包含一个名为“有形VisualStudio自动化助手”的模板。 将此选项包括到模板中,并使用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"))
            {
                ...
            }
        }
    }
    #>
    
    a.FullName==“输入”))
    {
    ...
    }
    }
    }
    #>
    

  • 希望有帮助

    供参考;还有roslyn,它进行text=>语法树转换,可以用于此。您还可以在T4中定义新闻模型,并从中生成所有变体,以避免外部工具或反射。