如何在 Realm-dotnet 中存储 System.Collections.Generic.Dictionary [英] How to store a System.Collections.Generic.Dictionary in realm-dotnet

查看:44
本文介绍了如何在 Realm-dotnet 中存储 System.Collections.Generic.Dictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 Realm .NET 集成到我的 uwp 项目中,我想知道是否有任何方法可以在 Realm-dotnet 库中存储 System.Collections.Generic.Dictionary.我试过这个:

I m trying to integrate Realm .NET in my uwp project and I would like to know if there is any way to store a System.Collections.Generic.Dictionary in realm-dotnet base. I tried this :

 public class Training : RealmObject
{
    public int Id { get; set; }
    public int Id_document { get; set; }
    public IDictionary<string, string>  Names { get; set;}
} 

但我收到此错误:

错误 Fody/RealmWeaver:Training.Name 是一个尚不支持的System.Collections.Generic.IDictionary`2".

Error Fody/RealmWeaver: Training.Name is a 'System.Collections.Generic.IDictionary`2' which is not yet supported.

感谢提前,

推荐答案

基本请求

没有办法将 System.Collections.Generic.Dictionary 直接存储到 Realm 中.
在 Realm 官网你可以找到你要搜索的所有信息,例如 此处 您可以找到支持的数据类型的完整列表(也是集合).

Base request

There isn't a way to directly store a System.Collections.Generic.Dictionary into Realm.
On the Realm official website you can find all the informations that you're searching, as an example, here you can find the full list of the supported data types (Collections too).

为了使用类似于 Dictionary 的结构来保存数据,您需要使用从 RealmObject 继承的自定义类,其中包含两个 IList<;T> 属性,如:

In order to save data with a structure as kind as a Dictionary, you would want to use a custom class that inherits from RealmObject with two IList<T> properties, such as:

public class RealmDictionary : RealmObject {
    public IList<T> Keys { get; }
    public IList<T> Values { get; }
}

在您要存储Dictionary 的类中,使用上述RealmDictionary 类的实例:

An in your class where you want to store the Dictionary, use an instance of the above RealmDictionary class:

...
public RealmDictionary Names { get; set; }
...

更新

(使用 NewtonsoftJson)
如果必须将数据序列化为 Json 字符串,则可以将基类设置为:

Update

(Using NewtonsoftJson)
If you must serialize the data into a Json string, you can setup your base class as:

...
[JsonIgnore]
public RealmDictionary RealmNames { get; set; }
public Dictionary<string,string> Names {
    get {
        return RealmNames.AsDictionary
    }   
}
...

然后将一个属性/方法添加到 RealmDictionary 类中,该属性/方法构造一个带有值的字典,类似的东西..

Then adding into the RealmDictionary class a property/method that constructs a dictionary with the values, something along the lines..

public Dictionary<string,string> AsDictionary {
    get {
        Dictionary<string,string> temp = new Dictionary<>();
        for(int i = 0; i < Keys.Count; i++){
            temp.Add(Keys[i], Values[i]);
        }
        return temp;
    }
}

这篇关于如何在 Realm-dotnet 中存储 System.Collections.Generic.Dictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆