检查数组是否为空并有内容
本文关键字:数组 是否 检查 | 更新日期: 2023-09-27 17:50:34
我正在寻找一些代码改进。我目前有以下代码:
if (pMyDocAction.s_locatie_st != null)
{
String[] myLocaties = Globals.GlobalTools.DeserializeValueToStringArray(pMyDocAction.s_locatie_st);
if (myLocaties != null)
if (myLocaties.Length > 0)
row.Locatie = myLocaties[0];
else
row.Locatie = String.Empty;
else
row.Locatie = String.Empty;
}
else
row.Locatie = String.Empty;
Mylocaties
是Array of String
,这个不能改变。我如何缩短这段代码(或者我如何将!= null
和.length > 0
组合在一起?
感谢
您可以使用条件运算符,并像这样编写语句:
row.Locatie = (myLocaties != null &&
myLocaties.Length > 0) ? myLocaties[0] : String.Empty
我建议你创建一个小的扩展方法:
public static class ArrayExtension{
public static bool HasContent<T>(Array<T> array) {
return array != null && array.Length > 0;
}
}
然后你可以检查:
int[] x = null;
x.HasContent(); // false
string[] strs = new string[] {};
strs.HasContent(); // false
string[] strs2 = new string[] {"foo", "bar" };
strs.HasContent(); // true
可以通过扩展来简化语法:
public static class ArrayExtension{
public static T FirstValueOrDefault<T>(Array<T> array, T @default) {
if( array != null && array.Length >0 ){
return array[0];
}
else {
return @default;
}
}
}
int[] x = null;
int y = x.FirstValueOrDefault(42); // 42
string[] strs = new string[] {};
string some = strs.FirstValueOrDefault("default"); // default
string[] strs2 = new string[] {"foo", "bar" };
string some2 = strs.FirstValueOrDefault("default"); // foo
在两个条件下使用&&
运算符,它将进行短路求值,如果第一个条件为假,它将不计算第二个条件。
if (myLocaties != null && myLocaties.Length > 0)
{
row.Locatie = myLocaties[0];
}
else
{
row.Locatie = String.Empty;
}
由于所有其他答案似乎都忽略了if (pMyDocAction.s_locatie_st != null)
,因此像这样的答案似乎是最可重用的:
row.Locatie = DeserializeLocation(pMyDocAction.s_locatie_st);
string DeserializeLocation(string locationString)
{
var result = "";
if (!string.IsNullOrEmpty(locationString))
{
String[] deserializedLocations =
Globals.GlobalTools.DeserializeValueToStringArray(locationString);
if (deserializedLocations != null && deserializedLocations.Any())
{
result = deserializedLocations[0];
}
}
return result;
}
你甚至可以考虑把这个方法放在你的" GlobalTools
"类中,这样你就可以在任何地方调用它,当你需要反序列化一个可能为空的序列化位置字符串到一个位置字符串