gpt4 book ai didi

c# - 检查字符串是否不为空且不为空时,顺序重要吗?

转载 作者:行者123 更新时间:2023-12-04 00:06:54 26 4
gpt4 key购买 nike

我在看一个关于 C# 中三元运算符的教程,老师说你应该先检查字符串是否不为空,但没有解释原因。我尝试先检查字符串是否不为空,并得到与他相同的结果,所以这有关系吗?

public class TernaryChallenge : MonoBehaviour
{
public string playerName;
void OnDisable()
{
string name = (playerName != "" && playerName != null) ? "Hello " + playerName : "Hello Player 1!";
Debug.Log(name);
}
}

最佳答案

不,在这种情况下,首先检查是否为空或为 null 并不重要。您可以使用 string.IsNullOrEmpty 方法代替并合并两个条件:

!string.IsNullOrEmpty(playerName) ? Hello " + playerName : "Hello Player 1!";

如果您要访问字符串的属性,则顺序很重要,例如:

if(playerName.Length < 10 && playerName != null)

如果 playerName 为 null,则此操作将会失败,因为您尝试访问 null 对象上的 Length 属性。正确的检查方法是:

if(playerName != null && playerName.Length < 10)

或者您可以使用 C# 的 null-conditional operator 来缩短它:

if(playerName?.Length < 10)

关于c# - 检查字符串是否不为空且不为空时,顺序重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51910885/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com