Protobuf(de)序列化

时间:2014-10-20 16:11:03

标签: c# serialization protobuf-net

我有类似这样的课程设置(我删除了很多其他属性,因为它们与我的问题无关......):

public class Record : IRecord
{
    /// <summary>
    /// The type of recovery record and data needed to recover this record.
    /// </summary>
    [DataMember(Order = 1)]
    public IRecord Entry { get; private set; }

    [IgnoreDataMember]
    public object Entry
    {
        get { return Entry; }
    }
}

[ProtoContract
    , ProtoInclude(2, typeof(CaseRecord))
    , ProtoInclude(3, typeof(UserRecord))
]
public interface IRecord: IEntry
{
}

public interface IEntry
{
    long EntryId { get; set; }
    long DataSourceId { get; set; }
}

public class UserRecord : RecordEntry<UserRecord> 
{
    // ...other datamembers...

    [IgnoreDataMember]
    public override long EntryId { get; set; }
    [IgnoreDataMember]
    public override long DataSourceId { get; set; } 
}

[DataContract]
public abstract class RecordEntry<T> : RType<T>, IRecord
    where T : RType<T>, new()
{
    // other datamembers...
    public abstract long EntryId { get; set; }
    public abstract long DataSourceId { get; set; }
}

我(de)序列化记录流,如下:

Serializer.SerializeWithLengthPrefix(_stream, record, PrefixStyle.Base128);

Serializer.DeserializeWithLengthPrefix<Record>(_stream, PrefixStyle.Base128);

但是,当我尝试反序列化时,我的Record对象(类型为UserRecord)会返回EntryIdDataSourceId的值0和我{m}不完全确定为什么。我从[IgnoreDataMember]Entry ID中删除了DataSource,但我仍然在保留时获得值0。正确填充对象的所有其他属性。

[TestMethod] ...

中创建用户记录
userRecord1 = new UserRecord()
{
    // ...other datamembers
    EntryId = 123456789,
    DataSourceId = 123456789,
};

1 个答案:

答案 0 :(得分:0)

http://thwadi.blogspot.com/2013/07/using-protobuff-net-with-inheritance.html

找到上述文章并将ProtoMember属性添加到EntryIdDataSourceId,我就能获得正确的值。