【问题标题】:Accessing value by key in Directory<system.String, system.Object> - C# Unity Dictionary在 Directory<system.String, system.Object> 中按键访问值 - C# Unity Dictionary
【发布时间】:2017-10-03 04:09:26
【问题描述】:

这段代码监听我的 Firebase 中的任何更改,并在检测到更改时触发 HandleListChange():

void SetRoomListListener()
{
    FirebaseDatabase.DefaultInstance
        .GetReference ("Rooms")
        .ValueChanged += HandleListChange;
}

我的HandleListChange() 现在看起来像这样:

void HandleListChange(object sender, ValueChangedEventArgs args)
{
    if (args.DatabaseError != null) {
        Debug.LogError (args.DatabaseError.Message);
        return;
    }

    // We got the new data
    foreach (DataSnapshot room in args.Snapshot.Children) 
    {
        string roomName = room.Key;

        foreach (KeyValuePair<string, Object> info in room.Value) 
        {
            Debug.Log (info);
        }
    }
}

调试room.Key 给了我想要的房间名称,room.Value 返回某种字典 -> Dictionary2[System.String, System.Object]。我想使用一个键访问该字典中的一个值,比如说room.Value["size"],但我从 foreach 循环foreach statement cannot operate on variables of type object because it does not contain a definition for GetEnumerator or is inaccessible 中得到这个错误。我已经尝试了很多其他方法,但无法使其正常工作。这是我第一次同时使用:目录和firebase,所以我不知道发生了什么。用于 Unity 的 Firebase API 非常小,互联网也没有多大帮助。我猜这个问题更可能出现在 C# 端,而不是 Unity 或 Firebase 端。如何使用该目录中的键访问我的值?谢谢。

【问题讨论】:

    标签: c# dictionary firebase unity3d firebase-realtime-database


    【解决方案1】:

    documentation看来DataSnapshot.Value返回一个object,可能封装了不同的原生类型。

    如果您确定 room.Value 包含字典,那么您应该只转换它,然后像 C# 中的任何字典一样访问其成员:

    var dictionary = (IDictionary<string, object>)room.Value;
    var exampleValue = dictionary["size"];
    

    【讨论】:

      猜你喜欢
      • 2012-04-22
      • 2015-08-14
      • 2017-04-29
      • 1970-01-01
      • 2021-06-17
      • 2015-11-02
      • 2021-09-16
      • 1970-01-01
      相关资源
      最近更新 更多