简体   繁体   中英

Accessing value by key in Directory<system.String, system.Object> - C# Unity Dictionary

This piece of code listens to any changes in my Firebase and fires HandleListChange() when it detects a change:

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

My HandleListChange() looks like this at the moment:

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);
        }
    }
}

Debugging room.Key gives me name of the room as I want it and room.Value returns some kind of dictionary -> Dictionary2[System.String, System.Object] . I want to access a value in that Dictionary using a key let's say room.Value["size"] but I get this error from the foreach-loop foreach statement cannot operate on variables of type object because it does not contain a definition for GetEnumerator or is inaccessible . I've tried quite a few other methods but can't get this to work. This is my first time working with both: directories and firebase, so I have no clue whats going on. Firebase API for Unity is quite minor and internet is not helping much either. I guess this problem is more likely on the C# side, not on Unity's or Firebase's. How can I access my values using a key in that directory? Thanks.

From the documentation it seems that DataSnapshot.Value returns an object , which may encapsulate different native types.

If you are sure room.Value contains a dictionary, then you should just cast it and then access its members like any dictionary in C#:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM