Xamarin.Forms中从Firestore检索含数组的Map字段的正确数据类型?
解决Firestore Map字段的C#类型映射问题
你之前使用List<(List<string> Item1, List<float> Item2, List<float> Item3)>的写法错误,核心原因是Firestore的Map是键值对结构,并非数组/列表类型,不能用List来对应。
以下是两种正确的类型表示方案:
方案1:强类型类(推荐)
创建一个与Firestore Map结构完全匹配的类,属性名需和Map的键严格一致(大小写敏感):
public class FirestoreMapData { public List<string> Item1 { get; set; } public List<float> Item2 { get; set; } public List<float> Item3 { get; set; } }
然后在你的文档实体类中,将目标字段声明为该类的类型:
public FirestoreMapData firestoreField { get; set; }
如果Firestore的键名和C#属性名不一致,可通过特性映射:
[FirestoreProperty("item1")] // 对应Firestore中的"item1"键 public List<string> Item1 { get; set; }
方案2:弱类型Dictionary
若不想额外创建类,可使用Dictionary<string, object>,后续手动转换值类型:
public Dictionary<string, object> firestoreField { get; set; }
使用时做类型转换:
var item1 = (List<string>)firestoreField["Item1"]; var item2 = (List<float>)firestoreField["Item2"]; var item3 = (List<float>)firestoreField["Item3"];
关键注意点
- 确认Firestore中存储的是Map类型,而非Array类型,结构不匹配会导致返回空值
- Firestore的number类型如果是整数,需用
List<int>;如果是浮点数,用List<float>或List<double>,根据实际存储值调整类型
内容的提问来源于stack exchange,提问作者Costas
相关产品推荐
相关产品推荐

