首页 > 解决方案 > 我可以在 c# 中为 Realm 自定义 getter 和 setter 吗?

问题描述

我有一个RealmObject扩展类。它的一些属性声明如下:

public String Name { get; set; }
public int Age { get; set; }

当我保存对象时,这些存储在 Realm 数据库中。对于另一个,我需要一个这样的自定义设置器:

private double _amount;
public double Amount
{
    get { return _amount; }
    set
    {
        _amount = value;
        NotifyPropertyChanged();
    }
}

而这个没有被存储。有人能帮我吗?

提前致谢

标签: c#realm

解决方案


Realm 将仅存储具有自动 getter 和 setter 的属性,因为它使用编译时 IL 生成来用对数据库的调用来替换实现。如果要自定义 getter 和 setter,则需要将字段定义为属性:

private double _amount { get; set; }
public double Amount
{
    get { return _amount; }
    set { ... }
}

Realm 将使用该_amount属性,而您的应用程序可以使用公共属性Amount

附带说明一下,您不需要调用NotifyPropertyChanged持久属性,因为 Realm 已经INotifyPropertyChanged为您处理了事件。因此public double Amount { get; set; }足以引发属性更改通知。


推荐阅读