[英]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: 这段代码侦听我的Firebase中的任何更改,并在检测到更改时触发HandleListChange():
void SetRoomListListener()
{
FirebaseDatabase.DefaultInstance
.GetReference ("Rooms")
.ValueChanged += HandleListChange;
}
My HandleListChange()
looks like this at the moment: 我的
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);
}
}
}
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]
. 调试
room.Key
给我我想要的房间名称,而room.Value
返回某种字典-> 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
. 我想使用一个键访问
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
。 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,所以我不知道发生了什么。 Firebase API for Unity is quite minor and internet is not helping much either.
用于Unity的Firebase API很小,互联网也没有太大帮助。 I guess this problem is more likely on the C# side, not on Unity's or Firebase's.
我想这个问题更有可能发生在C#端,而不是Unity或Firebase。 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. 从文档看来,
DataSnapshot.Value
返回一个object
,该object
可以封装不同的本机类型。
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#: 如果确定
room.Value
包含字典,则应将其room.Value
,然后像C#中的任何字典一样访问其成员:
var dictionary = (IDictionary<string, object>)room.Value;
var exampleValue = dictionary["size"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.