如何在.NET中生成代码模板时,使用非布尔类型的条件语句。

huangapple go评论124阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2023年4月17日 18:30:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定