我正在看有关C#中三元运算符的教程,老师说您应该首先检查字符串是否不为null,但没有解释原因。我试过先检查字符串是否不为空,并得到与他相同的结果,这有关系吗?
public class TernaryChallenge : MonoBehaviour
{
public string playerName;
void OnDisable()
{
string name = (playerName != "" && playerName != null) ? "Hello " + playerName : "Hello Player 1!";
Debug.Log(name);
}
}
非常感谢。
答案 0 :(得分:4)
否,在这种情况下,您是否先检查为空还是为null都没有关系。您可以改用string.IsNullOrEmpty
方法并合并两个条件:
!string.IsNullOrEmpty(playerName) ? Hello " + playerName : "Hello Player 1!";
如果要访问字符串的属性,则顺序很重要,例如:
if(playerName.Length < 10 && playerName != null)
如果playerName
为空,这将失败,因为您正在尝试访问空对象上的Length
属性。正确的检查方法是:
if(playerName != null && playerName.Length < 10)
或者您可以使用C#的null-conditional operator来缩短它:
if(playerName?.Length < 10)
答案 1 :(得分:1)
只有在您要在字符串字段上调用成员方法的情况下,才有意义,好像它为null一样,您将获得null引用异常。 在这种情况下,您可以按任何顺序检查null还是空。
我还建议使用内置的string.IsNullOrEmpty()方法。请参见以下基于您的代码编写的方法,以及单元测试。
public class TernaryChallenge
{
public string playerName;
public string OnDisable1()
{
string name = (playerName != "" && playerName != null) ? "Hello " +
playerName : "Hello Player 1!";
return name;
}
public string OnDisable2()
{
string name = (playerName != null && playerName != "") ? "Hello " +
playerName : "Hello Player 1!";
return name;
}
public string OnDisable3()
{
string name = !string.IsNullOrEmpty(playerName) ? "Hello " + playerName :
"Hello Player 1!";
return name;
}
[TestMethod]
public void TestMethod1()
{
var ternaryChallenge = new TernaryChallenge();
string actual = ternaryChallenge.OnDisable1();
string expected = "Hello Player 1!";
Assert.AreEqual(expected, actual, ignoreCase: false);
actual = ternaryChallenge.OnDisable2();
expected = "Hello Player 1!";
Assert.AreEqual(expected, actual, ignoreCase: false);
actual = ternaryChallenge.OnDisable3();
expected = "Hello Player 1!";
Assert.AreEqual(expected, actual, ignoreCase: false);
}
[TestMethod]
public void TestMethod2()
{
var ternaryChallenge = new TernaryChallenge
{
playerName = null
};
string actual = ternaryChallenge.OnDisable1();
string expected = "Hello Player 1!";
Assert.AreEqual(expected, actual, ignoreCase: false);
actual = ternaryChallenge.OnDisable2();
expected = "Hello Player 1!";
Assert.AreEqual(expected, actual, ignoreCase: false);
actual = ternaryChallenge.OnDisable3();
expected = "Hello Player 1!";
Assert.AreEqual(expected, actual, ignoreCase: false);
}