我正在尝试使用文本模板实用程序方法(如WriteLine,PushIndent,PopIndent)在T4模板中编写一个类.但是,如果我尝试在我的类中调用这些方法,我将收到编译器错误说明
编译变换:无法访问经由嵌套类型"Microsoft.VisualStudio.TextTemplatingBF13B4A5FBA992E5EF81A8A7A4EACCAC3F7698E169D0F7825ED4F22A28C7C52C2B766D83F4C5ACA13E0DE0B3152B6D966E34EB8C5FC677E145F55BE0485406EC.GeneratedTextTransformation.ClassGenerator"外类型"Microsoft.VisualStudio.TextTemplating.TextTransformation"的非静态成员
MCVE(最小完整可验证示例)如下所示:
<#+
public void FunctionSample()
{
WriteLine("Hello"); // This works fine
}
public class SampleClass
{
public static void StaticMethodSample()
{
WriteLine("Hello"); // This does not compile
}
public void InstanceMethodSample()
{
WriteLine("Hello"); // This does not compile either
}
}
#>
Run Code Online (Sandbox Code Playgroud)
有没有办法在类范围内访问这些实用程序方法,还是我必须使用自由函数?
(我在Visual Studio 2015社区上运行)
正如PetSerAl在评论中指出的那样,您可以在类功能控制块中的任何"自由函数"中调用T4实用程序方法,因为它们是从TextTransformation基类继承的,即这些自由函数并非完全免费,它们是从中派生的隐式创建的类的范围TextTransformation.这就是为什么你也可以访问this这些功能.
因此,如果要在T4模板中定义的另一个类中使用实用程序方法(此类实际上是嵌套的子类),则必须将TextTransformation的引用传递给它,例如:
<#
var @object = new SampleClass(this); // Pass 'this' (TextTransformation) to the constructor
@object.SayHello();
#>
<#+
public class SampleClass // This is actually a nested child class in T4 templates
{
private readonly TextTransformation _writer;
public SampleClass(TextTransformation writer)
{
if (writer == null) throw new ArgumentNullException("writer");
_writer = writer;
}
public void SayHello()
{
_writer.WriteLine("Hello");
}
}
#>
Run Code Online (Sandbox Code Playgroud)
可以在MSDN库中找到更多信息.