Docs 菜单
Docs 主页
/ /
支持的数据类型

集 - .NET SDK

10.2.0 版本中的新增功能

Realm设立(如C# HashSet<> )是 ICollection<> IEnumerable<> 的实施。它支持除集合之外的任何Realm类型的值。要定义设立,请使用仅限 getter 的ISet<TValue> 属性,其中TValue 是任何受支持的类型。

从数据库中删除对象会将其从其存在的所有集中删除。 因此,对象集绝不会包含 null 对象。 但是,基元类型集可以包含 null 值。 如果您不想在集合中允许 null 值,则可以在集合声明中使用不可为 null 的类型(例如,使用ISet<double>而不是ISet<double?> )。 如果您使用的是较旧的模式类型定义(您的类派生自RealmObject基类),或者未启用可空性,并且集合包含可引用类型,例如stringbyte[]

重要

不支持同步

仅限本地 Realm 支持可为 null(可选)值的集合,但Sync不支持。

以下代码显示了集合类型的示例:

public partial class Inventory : IRealmObject
{
// A Set can contain any Realm-supported type, including
// objects that inherit from RealmObject
public ISet<Plant> PlantSet { get; }
public ISet<double> DoubleSet { get; }
// Nullable types are supported in local-only
// Realms, but not with Sync
public ISet<int?> NullableIntsSet { get; }
public ISet<string> RequiredStrings { get; }
}

以下代码演示了如何创建、写入和读取集合。

var inventory = new Inventory();
inventory.PlantSet.Add(new Plant() { Name = "Prickly Pear" });
inventory.DoubleSet.Add(123.45);
realm.Write(() =>
{
realm.Add<Inventory>(inventory);
});
// convert the Plant Set to an IQueryable and apply a filter
var pricklyPear = inventory.PlantSet.AsRealmQueryable()
.Where(p => p.Name == "Prickly Pear");
// Alternatively, apply a filter directly on the Plant Set
var pricklyPearPlants = inventory.PlantSet
.Filter("Name == 'Prickly Pear'");
// Find all Inventory items that have at least one value in their
// DoubleSet that is larger than 5
var moreThan100 = realm.All<Inventory>()
.Filter("DoubleSet.@values > 100");

您可以使用设立上的INotifyCollectionChanged.CollectionChanged事件来监视该设立的更改,并使用INotifyPropertyChanged.PropertyChanged事件来监视该设立特定属性的更改。

在以下代码示例中,我们有一个类,它有名为 StringSetISet<string> 属性。我们为 CollectionChangedPropertyChanged 事件设置事件处理程序:

var stringSet = container.StringSet.AsRealmCollection();
stringSet.CollectionChanged += (sender, e) =>
{
Console.WriteLine($"Set {sender} changed: {e.Action}");
};
stringSet.PropertyChanged += (sender, e) =>
{
Console.WriteLine($"Property changed on {sender}: {e.PropertyName}");
};

后退

字典

在此页面上