1

我正在使用 Unity 应用程序并使用 C# 使用 Google Firebase。在某一时刻,我必须编辑现有信息或添加新信息。为了做到这一点,我必须检查我的快照中是否存在节点,但我找不到这样做的函数。

HasChild() 总是返回 true,所以它没有帮助。我已经搜索过并且函数 exists() 总是被提及为最佳选项,但是当我尝试使用它时(写为“exists”或“Exists”),我收到以下错误: error CS1061: Type 'Firebase.Database.DataSnapshot' does not contain a definition for 'Exists' and no extension method 'Exists' of type 'Firebase.Database.DataSnapshot' could be found. Are you missing an assembly reference?(...) does not contain a definition for 'exists' (...)

// The data structure looks like:
// .../questions
//      question_0
//          index = 0
//          other information...
//      question_2
//          index = 3
//          other information...
//      question_3
//          index = 5
//          other information...
//      question_6
//          index = 4
//          other information...

// The code I'm using:

public static DataSnapshot dbSnapshot; // I get this from an Event Listener

public void MyMethod(){
    int i = 0;
    bool done = false;
    do {
        string path = "questions/question_" + i.ToString() + "/index";
            if (dbSnapshot.Child(path).Exist()){  // The line that does not work!
            long newValue = (long) dbSnapshot.Child(path).Value;
            // If true, I'll do something here with this value
        } else {
            // If not, I'll do something else here
        }


        // at some point later "done" becomes true, ending loop
        // this part of the code works just fine
    } while (!done);
}

无法使用 Exist(),我尝试检查空值:

if (dbSnapshot.Child(path).Value != null)

但是每当我遇到一个不存在的 question_i 时,我都会收到一个错误:InvalidCastException: Specified cast is not valid.此错误不会发生在 if-satament 本身内,而是发生在下一行。看起来 ...Value != null 正在返回 true,因此在下一行应用程序尝试获取该值,但由于它不存在,我得到了错误。

那么,如何在不查找空值或使用 Exist() 和 HasChild() 函数的情况下检查节点是否存在?

4

0 回答 0