英文:
Is it possible to define field types when adding fields and values to a document with C#?
问题
使用Dictionary表示文档是一种向其添加字段和数值的方法。是否有其他方法,可以同时定义字段类型?
例如,可以使用字典:
Dictionary<string, object> data = new Dictionary<string, object>
{
{ "field1", var1 },
{ "field2", var2 },
};
然后通过await doc.SetAsync(data);将字段及其值添加到目标文档。
但是否有一种方法可以定义字段的类型呢?
英文:
Representing a document with a Dictionary is one way to add fields and values to it.
Is there any alternative which would also include defining the Field type?
For example a dictionary can be:
Dictionary<string, object> data = new Dictionary<string, object>
{
{ "field1", var1 },
{ "field2", var2 },
};
Then by using await doc.SetAsync(data); the fields with their values will be added to the targeted document.
Is there a way though to define the types of the fields?
答案1
得分: 1
你不能在任何编程语言中明确设置类型。字段的类型是由你提供的数据的类型确定的(在你的情况下是var1和var2)。如果你想确保字段的类型,那么就由你提前转换值。例如,如果你有一个字符串,但你想要一个数字字段,你需要在将该字符串提供给Firestore之前将其转换为数字。
英文:
You cannot set types explicitly in any language. They types of any fields come from the types of the data you provide (in your case, var1 and var2. If you want to ensure the type of any field, then it's up to you to convert the values ahead of time. For example, if you have a string, but you want a number field out of it, you will need to convert that string to a number before you give it to Firestore.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论