基于值为null或"00"从get返回

Sam*_*tar 0 c#

有人能告诉我这是否是有效的代码:

get
{
    return string.IsNullOrEmpty(TopicID) ? null : 
           TopicID == "00" ? "All Topics" :     
           int.Parse(TopicID).ToString();
}
Run Code Online (Sandbox Code Playgroud)

我希望get返回null,如果它是"00"则返回单词"All Topics"或返回没有前导零的数字.

代码看起来很乱,但我不确定是否有更简洁的方法让我编写代码.

Jon*_*eet 5

编译器会告诉你它是否是有效的代码:)

其他人可能建议使用if语句而不是条件运算符.我对这里的条件运算符很满意,但为了清晰起见,我会更改格式:

return string.IsNullOrEmpty(TopicID) ? null 
    : TopicID == "00" ? "All Topics" 
    : int.Parse(TopicID).ToString();
Run Code Online (Sandbox Code Playgroud)

这是这种模式的一个例子:

[assignment or return] = condition-1 ? value-1
    : condition-2 ? value-2
    : condition-3 ? value-3
      ...
    : fallback-value;
Run Code Online (Sandbox Code Playgroud)

我发现这种模式非常有用和可读.事实上,它看起来有点像F#完全是巧合的:)