簡體   English   中英

通過目錄中的鍵訪問值 <system.String, system.Object> -C#Unity字典

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

這段代碼偵聽我的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。 如何使用該目錄中的鍵訪問值? 謝謝。

文檔看來, DataSnapshot.Value返回一個object ,該object可以封裝不同的本機類型。

如果確定room.Value包含字典,則應將其room.Value ,然后像C#中的任何字典一樣訪問其成員:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM