开发者

private initialized variable not initializing

I have a datacontract on an inherited, partial class like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace Domain
{
  [DataContract]
  public partial class IdCard : DomainObject<System.Int64>
  {
    private Group _grp;

    [DataMember]
    public virtual Group Grp
    {
        get { return _grp; }
        set { _grp = value; }
    }

    private bool _unproxized = true;
    public override object UnProxy()
  开发者_开发问答  {
        if (this._unproxized)  // this prevents stackoverflow with cyclical references
        {
            this.Grp = (Group)this.Grp.UnProxy();
            this._unproxized = false;
        }

        return this;
    }
  }
}

For some reason, the _unproxized is never set to true; Any ideas why?

I know I can simply switch the logic around, but I'm curious why the member variable is not being initialized.


Has the instance that you are looking at been deserialized? During standard DataContract de-serialization no constructors are called and only DataMembers are assigned. The variable that you are looking at is not marked as a DataMember.

This thread describes the implementation of the behavior that you are seeing using an almost identical example.


It's because when deserialising, the DataContract serialiser uses a type of reflection to create completely uninitialised object instances, to which it then applies data. That's why the DataContract serialiser doesn't require a parameterless constructor. (Even if you add one, it won't get called). If you mark the _unproxied field with a [DataMember] attribute, it will be true.


My suspicion is you are using web/service references. In this case the code (private variable) never gets to the client.


try to assign varibles in a constructor like this:

public IdCard()
{
    _unproxized = true;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜