简体   繁体   English

在StringBuilder中使用布尔表达式

[英]Using a Boolean Expression in a StringBuilder

I'm using a string builder to build some SQL Scripts. 我正在使用字符串生成器来构建一些SQL脚本。 I have a few Boolean Properties that I would like to test and then output different text based on true/false. 我有一些要测试的布尔属性,然后根据true / false输出不同的文本。 I've you the C# syntax below when assigning a value to a variable, but it isn't working for this particular situation. 在为变量赋值时,我使用了下面的C#语法,但是在这种特定情况下它不起作用。 Any ideas? 有任何想法吗?

What I'm used to doing: 我已经习惯了:

string someText = (dbInfo.IsIdentity) ? "First Option" : "Second Option";

Trying to duplicate the same thing inside a StringBuilder method, but this isn't working.. 试图在StringBuilder方法中复制相同的内容,但这不起作用。

script.Append("sometext" + (dbInfo.IsIdentity) ? " IDENTITY(1,1)" : "");

添加括号:

script.Append("sometext" + ((dbInfo.IsIdentity) ? " IDENTITY(1,1)" : ""));

What about this? 那这个呢?

script.Append( "sometext" );
script.Append( dbInfo.IsIdentity ? " IDENTITY(1,1)" : "" );

Other from stating that if you have a stringbuilder you should use it to concatenate strings. 除了指出如果您有stringbuilder之外,还应该使用它来连接字符串。

That said, the code bellow should work. 也就是说,下面的代码应该可以工作。

script.Append("sometext");
script.Append(dbInfo.IsIdentity ? " IDENTITY(1,1)" : "");

In this particular case you could also do: 在这种情况下,您还可以执行以下操作:

script.Append("sometext");
if(dbInfo.IsIdentity) script.Append(" IDENTITY(1,1)");

附加括号甚至更好使用AppendFormat

script.AppendFormat("sometext{0}", dbInfo.IsIdentity ? " IDENTITY(1,1)" : "");

Just a hunch but I think you need some more brackets: 只是预感,但我认为您需要更多的括号:

script.Append("sometext" + ((dbInfo.IsIdentity) ? " IDENTITY(1,1)" : ""));

I would urge you to use a temporary variable for readability sake. 出于可读性考虑,我强烈建议您使用一个临时变量。

First, I would try wrapping the if/then/else in a set of parenthesis and see if that fixes the problem. 首先,我尝试将if / then / else包装在一组括号中,看看是否能解决问题。 It may be a problem with the order in which that expression is being evaluated. 表达式的计算顺序可能有问题。

一个快速的建议:如果要像这样生成SQL,与使用直接C#相比,使用StringString之类的模板来生成SQL可能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM