有几种方法可以解决这个问题,这里是一种。 ;-)
我会创建两个RealmObjects。一个定义数组的单个元素(在我的示例中由四个整数定义的Color)和一个包含这些数组元素的IList 的RealmObject。
示例领域对象:
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]