arrays - 是否可以将自定义大小的 int 数组数组保存为 RealmObject 的字段?

标签 arrays xamarin realm

基本上我需要这样的数据类型:

int[] list1 = new int[4] { 1, 2, 3, 4 };
int[] list2 = new int[4] { 5, 6, 7, 8 };
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[][] lists = new int[][] {  list1 ,  list2 ,  list3 ,  list4  };

具有 4 个整数的自定义大小数组。

那么我可以在 Realm 数据库中做吗?

感觉用 List<int[4]> 替换“自定义大小的数组”更好但我怀疑这是可能的。

最佳答案

有几种方法可以解决这个问题,这里是一种方法。 ;-)

我会创建两个 RealmObject。一个定义数组的单个元素(在我的示例中由四个整数定义的 Color)和一个包含这些元素的 IListRealmObject数组元素。

示例 Realm 对象:

public class Color : RealmObject
{
    public int R { get; set; }
    public int G { get; set; }
    public int B { get; set; }
    public int A { get; set; }

    public int[] RGBA
    {
        get { return new int[] { R, G, B, A }; }
        set { R = value[0]; G = value[1]; B = value[2]; A = value[3]; }
    }
}

public class MaterialColors : RealmObject
{
    public string Material { get; set; }
    public Color PrimaryColor { get; set; }
    public IList<Color> AlternativeColors { get; }
    public void AddAlts(Color[] ca)
    {
        for (int i = 0; i < ca.Length; i++)
        {
            AlternativeColors.Add(ca[i]);
        }
    }
}

使用示例:

using (var realm = Realm.GetInstance(new RealmConfiguration { SchemaVersion = 1 }))
{
    var primary = new Color { RGBA = new int[] { 1, 2, 3, 4 } };
    var alt1 = new Color { RGBA = new int[] { 5, 6, 7, 8 } };
    var alt2 = new Color { RGBA = new int[] { 1, 3, 2, 1 } };
    var alt3 = new Color { RGBA = new int[] { 5, 4, 3, 2 } };

    var material = new MaterialColors
    {
        Material = "StackOverflow",
        PrimaryColor = primary,
    };
    // Add array element one at a time... 
    material.AlternativeColors.Add(alt3);
    // Add multiple elements (array[]) via custom method...
    material.AddAlts(new Color[] { alt1, alt2 });

    realm.Write(() =>
    {
        realm.Add(material);    
    });

    var materials = realm.All<MaterialColors>();
    foreach (var aMaterial in materials)
    {
        Console.WriteLine($"Pri: [{aMaterial.PrimaryColor.RGBA[0]}:{aMaterial.PrimaryColor.RGBA[1]}:{aMaterial.PrimaryColor.RGBA[2]}:{aMaterial.PrimaryColor.RGBA[3]}]");
        foreach (var color in aMaterial.AlternativeColors)
        {
            Console.WriteLine($"Alt: [{color.RGBA[0]}:{color.RGBA[1]}:{color.RGBA[2]}:{color.RGBA[3]}]");
        }
    }
}

输出:

Pri: [1:2:3:4]
Alt: [5:4:3:2]
Alt: [5:6:7:8]
Alt: [1:3:2:1]

关于arrays - 是否可以将自定义大小的 int 数组数组保存为 RealmObject 的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41920861/

相关文章:

c# - 如何将 Observable Collection 的 Item 属性绑定(bind)到 Switch 状态?

iOS - 保存数据以便在应用程序外部轻松访问

macos - Realm 在编辑操作中可以与 Cocoa Binding 一起使用吗?

java - 如何计算数组的中位数?

Xamarin.Forms,如何使用我当前的 Xamarin.Forms 找到兼容版本的 Android 支持库

java - 如何针对两个条件执行 RealmQuery

realm - 在realm.io 中具有多个键列的对象

PHP - 从数组中获取元素的索引

python - 如何访问字典内数组内的项目索引?

显示表中最后一行值的 PHP 数组