英文:
How to use conditional statements with non boolean types when generating code templates in .NET
问题
public class MyClass
{
public string MyParameter { get; set; }
}
英文:
If MyParameter
is supplied, I want this code block generated. The problem is it never generates whether MyParameter
is supplied or not. It seems that conditional statements only work for boolean
parameters. In my case MyParameter
is of type string
.
public class MyClass
{
#if (MyParameter)
public string MyParameter { get; set; }
---#endif
}
I tried to do this
public class MyClass
{
#if (!string.IsNullOrEmpty(MyParameter))
public string MyParameter { get; set; }
---#endif
}
But unlike the first, this always generates even when MyParameter
is null or empty. I have set the defaultValue
for my parameter to ""
in template.json
but the condition still always evaluate as true
.
答案1
得分: 2
你可以在template.json
文件中添加一个计算设置,并在源代码中使用它。例如:
"MyParameter": {
"type": "parameter",
"datatype": "text",
"defaultValue": ""
...
},
"IsMyParameterEmpty": {
"type": "computed",
"value": "MyParameter == \"\""
}
然后在你的C#源代码中:
public class MyClass
{
#if (!IsMyParameterEmpty)
public string MyParameter { get; set; }
#endif
}
英文:
You can add a computed setting to your template.json
file and use that in your source. For example:
"MyParameter": {
"type": "parameter",
"datatype": "text",
"defaultValue": ""
...
},
"IsMyParameterEmpty": {
"type": "computed",
"value": "MyParameter == \"\""
}
Then in your C# source:
public class MyClass
{
#if (!IsMyParameterEmpty)
public string MyParameter { get; set; }
---#endif
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论