2017-06-21 67 views
-2

我最近碰到这段代码传来:

public void AppendTextColour(string text, Color color, bool AddNewLine = false) 
     { 
      rtbDisplay.SuspendLayout(); 
      rtbDisplay.SelectionColor = color; 
      rtbDisplay.AppendText(AddNewLine 
       ? $"{text}{Environment.NewLine}" 
       : text); 
      rtbDisplay.ScrollToCaret(); 
      rtbDisplay.ResumeLayout(); 
     } 

最使我着迷它是AppendText();这里有点重组:

rtbDisplay.AppendText(AddNewLine? $"{text}{Environment.NewLine}": text); 

我只能猜测问号用于实例化布尔值,但是这里的美元符号和双点符号是绝对模糊的。任何人都可以解剖这一点,并解释给我看?

我很抱歉,如果我有点模棱两可,但我无法在任何地方找到任何相关信息。 :/

+4

检查[三元操作C#文档](https://stackoverflow.com/documentation/c%23/18/operators/6029/ternary-operator#t=201706210748539600617)和[内插字符串](https://stackoverflow.com/documentation/c%23/ 24/C-沙皮p-6-0-features/49/string-interpolation#t = 201706210748003145712) –

+0

请参阅https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator *条件运算符*。 (它有时被称为三元运算符,但其实际名称是条件?:运算符) –

+1

顺便说一句,无论何时您试图在编程语言中查找奇怪运算符的名称,都可以尝试搜索**列表运营商**。 – cubrr

回答

0

这条线:

rtbDisplay.AppendText(AddNewLine? $"{text}{Environment.NewLine}": text); 

可以写为:

if (AddNewLine){ 
    rtbDisplay.AppendText(string.Format("{0}{1}",text, Environment.NewLine)); // or just (text + Environment.NewLine) 
} else { 
    rtbDisplay.AppendText(text); 
} 

它使用ternary operatorstring interpolation(在C#引入6)