鉴于我只看到少数有关Visual Studio模板参数逻辑的帖子,但没有深入解释,因此我觉得在这里发布这个问题。
根据MSDN文章,您可以向模板中添加自定义参数,如果要更改它们,可以使用向导(Wizard)进行更改。
在模板的任何文件中(除了模板文件本身),都可以根据参数添加逻辑。 逻辑只有三个关键字可用。 $if$(%expression%),$else$和$endif$。 因此,假设我在模板文件中有以下内容:
public string foo( string a )
{
return string.Format( @"foo( {0} );", a );
}
我们想要添加一些逻辑,来确定我们是否想要检查 "a" 是否为 null 或空
public string foo( string a )
{
$if$ ( $shouldCheckForNullOrEmpty$ == true )
if ( !string.IsNullOrEmpty( a ) )
$endif$
return string.Format( @"foo( {0} );", a );
}
当然,你可能想要为if语句添加大括号,所以你可能需要多个逻辑块。
这并不太难,但有一些技巧。$if$检查字符串匹配,即shouldCheckForNullOrEmpty必须等于"true"。虽然写成 $if$ ($shouldCheckForNullOrEmpty$ == "true") 看起来很诱人,但这样不起作用。
单个表达式的if语句非常简单,现在我们来看一个稍微复杂一点的例子:
public string foo( string a )
{
$if$ ( $parameterCheckMode$ == ifNullOrEmpty )
if ( !string.IsNullOrEmpty( a ) )
$else$ $if$ ( $parameterCheckMode$ == throwIfNullOrEmpty )
if ( string.IsNullOrEmpty( a ) )
throw new ArgumentException();
$endif$ $endif$
return string.Format( @"foo( {0} );", a );
}
你可能已经注意到,这是一个针对参数 mode 的 switch 语句。你可能会发现没有 $elseif$ 关键字,因此你需要使用 $else$ $if$,但最后必须添加一个额外的 $endif$。
最后,我还没有找到逻辑运算符 and 或 or 的符号。我通过使用逻辑等价来解决了这个问题:
and -> $if$ ( expression1 ) $if$ ( expression2 ) $endif $endif$
or -> $if$ ( expression1 ) statement $else$ $if$ statement $endif$ $endif$
希望这能帮助到某人。
.vstemplate
文件中使用“魔法”XML指令:<VSTemplate Type="Item" Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">。请注意其中关键的3.0.0
。模板中还有很多其他空格方面的古怪问题;更多信息可以在此线程中找到:http://stackoverflow.com/questions/1220389/whats-wrong-with-my-visual-studio-2008-template/1568717 - Sean Werkema