5

event返す がありますboolean。誰かがリッスンしている場合にのみイベントが発生するようにするために、null 条件演算子 (疑問符) を使用して呼び出します。ただし、これは、返されたブール値にも null 条件演算子を追加する必要があることを意味します。そして、それは後でifステートメントでそれを使用する方法を理解できないことを意味します. 誰もこれを処理する方法を知っていますか?

switch (someInt) 
{
    case 1:
        // Validate if the form is filled correctly.
        // The event returns true if that is the case.
        bool? isValid = ValidateStuff?.Invoke();

        if (isValid)
            // If passed validation go to next step in form 
            GoToNextStep?.Invoke();
        break; 

    // There are more cases, but you get the point
    (...)
}
4

4 に答える 4

1

isValid1 つのオプションは、値があるかどうかをテストすることです。

if (isValid.HasValue && (bool)isValid)

別のオプションはisValid、誰もあなたのイベントをリッスンしていないときにデフォルト値を与えることです。これは、null 合体演算子を使用して実行できます。

bool isValid = ValidateStuff?.Invoke() ?? true;   // assume it is valid when nobody listens
于 2017-06-13T09:39:54.103 に答える