在 Unity c# 脚本中检查 null/empty 数组
Checking for null/empty arrays in a Unity c# script
我有一个使用 WebGL 和 c# 的 Unity 游戏。
我是 运行 Unity 2020.2.6f1,据我所知使用的是 c# 7.3
我目前像这样检查 null 或空数组:
ObjectType[] myObjectTypeList = FindObjectsOfType<ObjectType>();
if(myObjectTypeList != null && myObjectTypeList.Length > 0)
{
...
}
但我读到在 c# 7+ 中你可以缩短为:
if(!(myObjectTypeList?.Length != 0))
{
...
}
当我使用 FindObjectsOfType
时,我可以在 Unity c# 脚本中执行此操作吗?
谢谢!
在 C#7 C# 8.0 中,您可以使用 is
运算符,并且您的 if
语句可能是
if (myObjectTypeList is {Length: > 0}){
// [...]
}
等于
if (myObjectTypeList != null && myObjectTypeList.Length > 0){
// [...]
}
编辑
这个答案是错误的。
Beginning with C# 8.0, you use a property pattern to match an expression's properties or fields against nested patterns [...]
此功能仅适用于 c#8.0 及更高版本。也就是说,这个答案仍然有效,因为 Unity Version 2020.2 uses Roslyn Compiler with C# 8.0 Language Support.
?.
被称为 Null Conditional Operator
。 a?.b
将解析为 b
,除非 a
为 null
,在这种情况下它解析为 null
。这个运算符实际上是自 C# 6.0 以来新增的。
如果您可以接受有关在 null 上调用扩展方法的警告,那么这应该有效:
public static class Extensions
{
public static bool NotNullHasItems<T> (this IEnumerable<T> collection)
{
if (collection == null)
{
return false;
}
return collection.Any();
}
}
为了测试这个,我使用了:
List<string> stuff = null;
var shouldBeFalse = stuff.NotNullHasItems();
stuff = new List<string>();
var shouldAlsoBeFalse = stuff.NotNullHasItems();
stuff.Add("test");
var shouldBeTrue = stuff.NotNullHasItems();
并且 shouldBeFalse
和 shouldAlsoBeFalse
最终都是 false
而 shouldBeTrue
是真的。
您可能想要一个更好的名字(也许颠倒逻辑并将其命名为 IsNullOrEmpty
以匹配 string.IsNullOrEmpty
)
我有一个使用 WebGL 和 c# 的 Unity 游戏。
我是 运行 Unity 2020.2.6f1,据我所知使用的是 c# 7.3
我目前像这样检查 null 或空数组:
ObjectType[] myObjectTypeList = FindObjectsOfType<ObjectType>();
if(myObjectTypeList != null && myObjectTypeList.Length > 0)
{
...
}
但我读到在 c# 7+ 中你可以缩短为:
if(!(myObjectTypeList?.Length != 0))
{
...
}
当我使用 FindObjectsOfType
时,我可以在 Unity c# 脚本中执行此操作吗?
谢谢!
在 C#7 C# 8.0 中,您可以使用 is
运算符,并且您的 if
语句可能是
if (myObjectTypeList is {Length: > 0}){
// [...]
}
等于
if (myObjectTypeList != null && myObjectTypeList.Length > 0){
// [...]
}
编辑
这个答案是错误的。
Beginning with C# 8.0, you use a property pattern to match an expression's properties or fields against nested patterns [...]
此功能仅适用于 c#8.0 及更高版本。也就是说,这个答案仍然有效,因为 Unity Version 2020.2 uses Roslyn Compiler with C# 8.0 Language Support.
?.
被称为 Null Conditional Operator
。 a?.b
将解析为 b
,除非 a
为 null
,在这种情况下它解析为 null
。这个运算符实际上是自 C# 6.0 以来新增的。
如果您可以接受有关在 null 上调用扩展方法的警告,那么这应该有效:
public static class Extensions
{
public static bool NotNullHasItems<T> (this IEnumerable<T> collection)
{
if (collection == null)
{
return false;
}
return collection.Any();
}
}
为了测试这个,我使用了:
List<string> stuff = null;
var shouldBeFalse = stuff.NotNullHasItems();
stuff = new List<string>();
var shouldAlsoBeFalse = stuff.NotNullHasItems();
stuff.Add("test");
var shouldBeTrue = stuff.NotNullHasItems();
并且 shouldBeFalse
和 shouldAlsoBeFalse
最终都是 false
而 shouldBeTrue
是真的。
您可能想要一个更好的名字(也许颠倒逻辑并将其命名为 IsNullOrEmpty
以匹配 string.IsNullOrEmpty
)