c# 错误:使用未分配的局部变量(上下文 Visual Studio T4 ENGINE)
在 C# 中(在 T4 模板的上下文中,请参阅 http://www.olegsych.com/2008/03/how-to-generate-multiple-outputs-from-single-t4-template/)我想做这个
<# String myTemplateVar;
#>
<# if (string.IsNullOrEmpty(myTemplateVar)) {
myTemplateVar= "name";
};
#>
我想给如果 myTemplateVar 尚未由另一个模板中的 T4 引擎的外部调用设置,则 myTemplateVar 的值将具有以下指令:
CallContext.SetData("myTemplate.myTemplateVar", ExternalTemplateVar);
但我什至无法在 C# 中编译,为什么?如何解决这个问题?
这种事情在 PHP 中很容易做到,我不明白为什么在 C# 中它看起来如此复杂。
更新:问题是,如果我初始化为 Null 或 Empty 以避免编译错误,我如何检测到该变量已由外部调用设置?
In C# (within the context of T4 template see http://www.olegsych.com/2008/03/how-to-generate-multiple-outputs-from-single-t4-template/) I want to do this
<# String myTemplateVar;
#>
<# if (string.IsNullOrEmpty(myTemplateVar)) {
myTemplateVar= "name";
};
#>
I want to give a value to myTemplateVar if myTemplateVar has not already been setup by an external call from T4 engine in another template which would have this instruction:
CallContext.SetData("myTemplate.myTemplateVar", ExternalTemplateVar);
But I cannot even compile in C# why ? How to fix this ?
This kind of stuff is easy to do in PHP I don't understand why in C# it seems so complicated.
Update: the problem is that if I initialize to either Null or Empty to avoid compilation error, how can I detect that the variable has been setup by an external call ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
上面定义的 myTemplateVar 变量位于模板底层类内部的方法范围(TransformText 方法内部)。如果您想要类级别,那么您可以使用类功能块,如下所示。
甚至类 static:
但是,对于 C# 中的引用类型,除了通过其 null 值或未设置之外,仍然无法判断该变量是否已设置。
The myTemplateVar variable as defined above is at method scope inside the class underlying the template (inside the TransformText method).If you'd like a class-level, then you could use a class feature block, like so.
or even a class static:
However, there's still no way to tell whether the variable has been set, other than by its null value or not though for a reference type in C#.
尝试:
以解决编译错误。
Try:
in order to resolve the compile error.
您是否尝试过为字符串指定默认值?如果它没有进入 if 块,它将保持未分配状态。
Have you tried giving your string a default value? If it does not get in the if block, it will remain unassigned.