C# 在内部使用 != 运算符 ?:

C# Using != operator inside ?:

我正在尝试了解不等式运算符 (!=) 的工作原理。我能理解操作员的基本知识。如果操作数不相等,则 return 为 "true",否则为 "false"。

但我似乎无法理解我们在编程中给出的这个特定示例 class:

  1. 我为 Unity 编辑器设置了 public 字符串,但我没有输入任何文本。
  2. 两个引号 ("") 表示在 public 字符串上输入文本。
  3. 但在这种情况下,条件必须为“真”?因为我没有输入任何文字

为什么条件 returning "false" 和控制台调试 "Hello Player 1"???是不是条件 "true" 因此条件运算符必须 return 第一个表达式 而不是 第二个表达式

public string playerName;

void OnDisable() {
    playerName = (playerName != "") ? playerName : "Player 1";
    Debug.Log("Hello " + playerName);

如果 playerNamenull,这与空字符串不同,""

如果你想检查是否为空,我建议如下:

playerName = !String.IsNullOrEmpty(playerName) ? playerName : "Player 1";

您的字符串可能是 null

我会用

playerName = !string.IsNullOrWhiteSpace(playerName) ? playerName: "Player 1";

让我们分解一下:

此表达式检查 playerName 是否不等于空字符串。如果它不是空字符串,则它 returns 是 playerName 的值。如果它 空字符串,则它 returns "Player 1" 代替。

(playerName != "") ? playerName : "Player 1";

所以:"If we have a valid player name, use that; otherwise, call him "玩家 1"。

然后我们将该表达式的结果分配回 playerName:

playerName = (playerName != "") ? playerName : "Player 1";

如果我们没有值,效果是使用默认值 playerName

我不喜欢为此使用条件表达式。在我看来,这是一个奇怪的、不清楚的成语。另外,正如其他人所指出的,您的 playerName 默认为 null 不等于空字符串 。这意味着如果您没有得到任何输入,您将得到 null 而不是 "Player 1"

这是相同的逻辑,更具可读性,同时检查 null:

if (String.IsNullOrEmpty(playerName)) {
    playerName  = "Player 1";
}

学习条件运算符很好,在 class 中,您可以学习。但是如果你回到你的教授那里说 "this is the same logic but it's more clear",他最好不要扣你任何分数。

也就是说,您最好知道为什么这是相同的逻辑,而不是随便从互联网上随便拿一些卡通机器人的说法。

我想你把数字 2 弄错了。
""表示空字符串,即包含0个字符的字符串。

由于您没有输入任何文本,playerName 等于 "",因此 playerName != "" returns false,这就是您看到的原因Hello Payer 1.