- 精通T4脚本要从读懂脚本的关键代码片段开始
1.1. 给类添加注释-->看懂类对应的代码:<#=codeStringGenerator.EntityClassOpening(entity)#>
替换前
WriteHeader(codeStringGenerator, fileManager);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
<#=codeStringGenerator.EntityClassOpening(entity)#>
替换后
WriteHeader(codeStringGenerator, fileManager);
string summary=string.Empty;
foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection))
{
fileManager.StartNewFile(entity.Name + ".cs");
BeginNamespace(code);
if(entity.Documentation !=null && entity.Documentation.Summary!=null)
summary=entity.Documentation.Summary;
else
summary=entity.Name;
#>
<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
/// <summary>
/// <#=summary#>
/// </summary>
<#=codeStringGenerator.EntityClassOpening(entity)#>
1.2. 给命名空间添加注释-->看懂引用的命名空间对应的代码:<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
该方法实现与于odeStringGenerator类下边。代码如下:
public string UsingDirectives(bool inHeader, bool includeCollections = true)
{
return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion())
? string.Format(
CultureInfo.InvariantCulture,
"{0}using System;{1}" +
"{2}"+"{3}",
inHeader ? Environment.NewLine : "",
includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "",
includeCollections ? (Environment.NewLine + "using System.Data;") : "",
inHeader ? "" : Environment.NewLine)
: "";
}
1.3. 给属性添加注释-->看懂属性的代码对应的代码:<#=codeStringGenerator.Property(edmProperty)#>
替换前:
foreach (var edmProperty in simpleProperties)
{
#>
<#=codeStringGenerator.Property(edmProperty)#>
替换后:
foreach (var edmProperty in simpleProperties)
{
if (edmProperty.Documentation != null && edmProperty.Documentation.Summary != null)
{
summary=edmProperty.Documentation.Summary;
}
else
{
summary="";
}
#>
/// <summary>
/// <#=summary#>
/// </summary>
<#=codeStringGenerator.Property(edmProperty)#>
1.4. 看懂命名空间namespace对应的代码:namespace <#=code.EscapeNamespace(codeNamespace)#>