簡體   English   中英

如何檢查 object 的一個值是否為 null

[英]How to check if one value of an object is null

我有一個帶有多個字符串的 object。
有沒有辦法檢查其中一個值是 null 還是所有值都已設置?
或者我必須這樣做:

if (!string.IsNullOrWhiteSpace(object.string1) || !string.IsNullOrWhiteSpace(object.string2) || !string.IsNullOrWhiteSpace(object.string3))
{

}

您可以將所有字符串收集到一個數組中,然后運行.Any()方法:

if (new[] { obj.string1, obj.string2, obj.string3 }.Any(string.IsNullOrWhiteSpace))
{
    
}

或者,您可以使用反射(這會影響代碼的性能)掃描 object 的所有字符串並檢查您的情況:

var anyEmpty = obj.GetType().GetProperties()
    .Any(x => x.PropertyType == typeof(string)
              && string.IsNullOrWhiteSpace(x.GetValue(obj) as string));

您可以使用 for 循環遍歷所有字符串並檢查它們是否為空。

編輯:您可能必須將所有字符串添加到數組或列表中,因為它們都有不同的名稱,如 string1、string2 和 string3

如果你經常這樣做,你可以寫一個方法來檢查它:

public static class Ensure
{
    public static bool NoneNullOrWhitespace(params string?[] items)
    {
        return !items.Any(string.IsNullOrWhiteSpace);
    }
}

對於您的情況,您會這樣稱呼:

if (Ensure.NoneNullOrWhitespace(object.string1, object.string2, object.string3))
{
    ...
}

如果您可以選擇為對象定義 class,則可以讓 class 本身處理“所有字符串不是 null 或空白”- 檢查:

public class MyObject
{
    public string String1 { get; set; }
    public string String2 { get; set; }
    public string String3 { get; set; }

    public bool StringsAreNotNullOrWhiteSpace => !Strings.Any(string.IsNullOrWhiteSpace);

    private string[] Strings => new[] { String1, String2, String3 };
}

並像這樣使用它:

var myObject = new MyObject();
//Populate myObject

if (myObject.StringsAreNotNullOrWhiteSpace)
{
    //Add myObject to list
}

StringsAreNotNullOrWhiteSpace的實現基本上是 @mickl 在他們的第一個建議中所做的,但返回相反的 bool 值。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM