質問

最初の行を削除したい:

                 !string.IsNullOrEmpty(cell.Text) 
.

これはどんな問題も発生しますか?

私はいくつかのコードでこれを横切って走った:

                if ((id % 2 == 0)
                    && !string.IsNullOrEmpty(cell.Text)
                    && !string.IsNullOrEmpty(cell.Text.Trim())
                    )
.

最初のString.InullorEmptyはスペースを含む文字列でfalseを返すと思います。 そしてTrim()を含む行はそれを大事にします。そのため、最初のIsnullorEmptyは無用です

しかし、私はトリムなしで行を削除する前に、私はグループによってそれを実行すると思いました。

役に立ちましたか?

解決

最初のIsNullorEmptyは、Trim()でNullReferenceExceptionをスローする前にNULL値をキャッチします。

しかし、より良い方法があります:

if ((id % 2 == 0) && !string.IsNullOrWhiteSpace(cell.Text))
.

他のヒント

cell.textがnullの場合、最初のチェックがない場合は例外があります。

.NET 4.0:

if (id % 2 == 0 && !string.IsNullOrWhiteSpace(cell.Text))
{
    ...
}
.

古いバージョンでは、最初のものとcell.TextがNULLの場合は、NULLインスタンスで.Trimを呼び出したときにNREを受信します。

またはあなたはこれを行うことができます:

if (id % 2 == 0 && string.IsNullOrWhiteSpace((cell.Text ?? string.Empty).Trim()))
{
    ...
}
.

またはさらに良く、拡張方法これを行う文字列タイプ:

if (id % 2 == 0 && !cell.Text.IsNullOrWhiteSpace())
{
    ...
}
.

これはこのように見えるかもしれません:

public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string value)
    {
        return string.IsNullOrEmpty((value ?? string.Empty).Trim());
    }
}
.

テストは、セルが最初にNULLではないことを確認することです。ヌル文字列

!string.IsNullOrWhitespace(call.Text)を使用して以前の2つのチェックをドロップしないのはなぜですか?

セル.textがnullになる可能性があり、スローと例外が発生する可能性があるため、最初のIsNullorEmptyだけを削除できません。 isNullorWhiteSpace .NET 4.0または退席している場合どちらもチェックします。

if ((id % 2 == 0) && !string.IsNullOrWhiteSpace(cell.Text))
.

cell.textがnullの場合、式String.IsNullorEmpty(cell.text.trim())は、セルでメソッドtrim()を実行しようとしているため、例外をスローします。

条件がある場合は、はるかに重要なのです.Cell.text!= null && cell.text.trim()!="" "

このような拡張方法を使用できます。

/// <summary>
/// Indicates whether the specified string is null or empty.
/// This methods internally uses string.IsNullOrEmpty by trimming the string first which string.IsNullOrEmpty doesn't.
/// .NET's default string.IsNullOrEmpty method return false if a string is just having one blank space.
/// For such cases this custom IsNullOrEmptyWithTrim method is useful.
/// </summary>
/// <returns><c>true</c> if the string is null or empty or just having blank spaces;<c>false</c> otherwise.</returns> 
public static bool IsNullOrEmptyWithTrim(this string value)
{
    bool isEmpty = string.IsNullOrEmpty(value);
    if (isEmpty)
    {
        return true;
    }
    return value.Trim().Length == 0;
}
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top