C#Console.Readline如果设置为默认值,如果为空

时间:2014-04-02 10:23:50

标签: c# console readline

Csharp的新秀有一个问题。如果我有

string phoneNumber = Console.ReadLine();

如果这是空白的话,我怎么速记写if / else来为该字符串添加“无电话号码”。

像php这样的东西

$phoneNumber = (empty($get_phonenumber) ? "no phone number" : $get_phonenumber);

2 个答案:

答案 0 :(得分:3)

如果没有输入任何内容,

Console.ReadLine()将返回一个空字符串。

var readLine = Console.ReadLine();
var phoneNumber = String.IsNullOrEmpty(readLine) ? "default" : readLine;

如果您使用的是.NET 4或更高版本,则可以使用String.IsNullOrWhiteSpace(readLine)来检测该行是否也只包含空格。

答案 1 :(得分:0)

您可以尝试:

string s;
string phone = String.IsNullOrEmpty(s=Console.ReadLine()) ? "no phone number": s;