在 C# 中使用“?”、“$”和“:”登录
Using the '?', '$' and ':' sign in C#
我最近遇到了这段代码:
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);
我只能猜测问号是用来实例化布尔值的,但是这里的美元符号和双点符号绝对是晦涩难懂的。任何人都可以剖析这一点并向我解释吗?
如果我有点模棱两可,我深表歉意,但我无法在任何地方找到任何相关信息。 :/
这一行:
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 operator and string interpolation(在 C# 6 中引入)
我最近遇到了这段代码:
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);
我只能猜测问号是用来实例化布尔值的,但是这里的美元符号和双点符号绝对是晦涩难懂的。任何人都可以剖析这一点并向我解释吗?
如果我有点模棱两可,我深表歉意,但我无法在任何地方找到任何相关信息。 :/
这一行:
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 operator and string interpolation(在 C# 6 中引入)