【问题标题】:Not calling function during deserialization反序列化期间不调用函数
【发布时间】:2012-05-14 08:41:26
【问题描述】:

有没有办法在类反序列化期间不调用函数,例如:

private int _number
public int Number
{
    get
    {
        return _number;
    }
    set
    {
        _number = value
        //do not call this function during deserialization
        CallAnotherFunction()
    }
}

当 MongoDB 反序列化对象并设置 Number 属性时,它正在调用 CallAnotherFunction(),因为它在集合中。是否有标志或任何可用于CallAnotherFunction() 在反序列化期间不会被调用的东西?目前它在反序列化期间每次都调用该函数并添加重复值。

【问题讨论】:

  • 我没有回答你的问题,但它表明你的设计是错误的——除了分配变量之外,你的设置器中不应该有副作用,否则你会遇到这些类型的问题.

标签: c# mongodb mongodb-.net-driver


【解决方案1】:

您可以控制 C# MongoDB 驱动程序如何序列化和反序列化对象。 在这种情况下,为属性本身的属性 instread 序列化支持字段应该可以解决您的问题。查看 MongoDB 文档中的this article,了解有关控制序列化的更多详细信息。

使用属性,您的源代码将如下所示:

[BsonElement("Number")]
private int _number

[BsonIgnore]
public int Number  
{
  get { return _number; }
  set {
    _number = value

    //do not call this function during deserialization
    CallAnotherFunction()
  }
}

或者,您可以设置自定义类映射。

BsonClassMap.RegisterClassMap<MyClass>(cm => {
   cm.AutoMap();
   cm.UnmapProperty(c => c.Number);
   cm.MapField("_number").SetElementName("Number");
});

【讨论】:

    猜你喜欢
    • 2019-09-08
    • 1970-01-01
    • 2010-10-14
    • 2011-10-18
    • 2017-07-16
    • 1970-01-01
    • 2017-02-11
    • 2012-09-12
    • 1970-01-01
    相关资源
    最近更新 更多