我正在尝试使用T4 Text Templating生成代码,但在运行脚本时,我收到以下错误:
Running transformation: System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.VisualStudio.TextTemplatingB0A58A4C85EA3D7032675015C6052C89.GeneratedTextTransformation.TransformText() at Microsoft.VisualStudio.TextTemplating.TransformationRunner.RunTransformation(TemplateProcessingSession session, String source, ITextTemplatingEngineHost host, String& result)
由于我不熟悉T4,我不确定在哪里寻找解决此问题的方法。
答案 0 :(得分:8)
您需要调试模板以找到NullReferenceException
发生的位置。 Tim Larson快速概述here,Oleg Sych有更多详细信息here,以及他在T4上的其他优秀博客文章。
这是短短版本:
<#@ template debug="true" #>
System.Diagnostics.Debugger.Launch();
System.Diagnostics.Debugger.Break();
这是一个简单的示例,可帮助在bar上调用ToString时捕获NullReferenceException
:
<#@ template debug="true" language="C#" #>
<#@ output extension=".txt" #>
<#
System.Diagnostics.Debugger.Launch();
System.Diagnostics.Debugger.Break();
object bar = null;
#>
foo<#= bar.ToString() #>
请务必检查第一个链接,因为在某些版本中,您需要将注册表项HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\DbgJITDebugLaunchSetting
更新为0x2
才能使事情正常运行。
答案 1 :(得分:1)
您可以调试T4模板。 MSDN在that上提供了一些帮助。
在调试模式下,您可以查看生成的类,以找出出错的地方。 T4保存生成的代码,程序集和PDB TEMP文件夹(%USERPROFILE%\ Local Settings \ Temp)。 .cs文件包含GeneratedTextTransformation的源代码。 .cmdline文件包含用于将.cs文件编译为.NET程序集的命令行选项(.dll文件)。