@ 17. 1 ~ 18/용어정리
비주얼 스튜디오의 텍스트 템플릿 사용해보기
namoeye
2017. 9. 21. 23:41
<# 안에 c#코드들을 넣어서 작동시킬 수 있다.
자세한 문법사용 내용은
https://msdn.microsoft.com/ko-kr/library/bb126545.aspx
test.cs 파일
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp2 { /// <summary> /// 여기에 test는 tt파일과 같은 이름의 클래스를 partial로 구분해서 정의하고 있는것 /// string name은 실제 tt파일내부에서 <#=name#>으로 사용하기 위해서이다. /// </summary> partial class test { private string name; public test(string name) { this.name = name; } } } | cs |
program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp2 { class Program { static void Main(string[] args) { //tt에서 생성된 클래스와 TestCode.cs에서 //partial로 확장된 클래스에 대해 생성한다. //단순히 생성까지만해서는 아무런 반응이 없다. var report = new test("DD"); //아래의 TransformText().ToString()을 하게되면 이때 비로소 //test.tt에 정의한 스크립트들이 실행된다. Console.WriteLine(report.TransformText().ToString()); Console.ReadLine(); } } } | cs |
test.tt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <#@ template language="C#" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> <#@ import namespace="System.IO"#> 안녕하세요 <#=name #> 입니다. <# int count = 0; foreach(var i in Directory.GetFiles(@"C:\")) { count++; var fi = new FileInfo(i); #> 파일<#=count #> : <#=fi.Name #> <# } #> | cs |
<# Standard control blocks #>
은 문을 포함할 수 있습니다.<#= Expression control blocks #>
은 식을 포함할 수 있습니다.<#+ Class feature control blocks #>
은 메서드, 필드 및 속성을 포함할 수 있습니다.
tt파일 내부에 count와 fi.Name은 바로 위에 <# ~ #>안에 있는 c# 코드가 실행되면서 사용할 수 있는 count와 fi를 <#=count #>, <#=fi.Name>
의 변수값에 넣는것 입니다.
실행결과