使用SoapFormatter序列化类的选择属性

时间:2009-11-30 15:15:33

标签: c# .net serialization soap

您好我需要序列化我班级的几个字段

class Foo
{
 Guid value1;
 decimal value2;
 SomeCustomEnum value3;
}

我可以逐个序列化所有字段:

            MemoryStream ms = new MemoryStream();
            SoapFormatter sf = new SoapFormatter();
            sf.Serialize(ms,value1;
            sf.Serialize(ms, value2);
            sf.Serialize(ms, value3);
            string data = Convert.ToBase64String(ms.ToArray());
            ms.Close();

1 个答案:

答案 0 :(得分:3)

使用[NonSerialized]标记您不想序列化的字段。这样你可以跳过第三方字段。

    [Serializable]
    class Foo
    {
        Guid value1;
        decimal value2;
        SomeCustomEnum value3;

        [NonSerialized]
        int Skip = 12;
    }

[编辑] 关于继承的评论之后的新例子。您可以手动控制序列化:

class Foo
{
    public Guid value1;
    public decimal value2;
    public SomeCustomEnum value3;
}

[Serializable]
class Bar : Foo, ISerializable
{
    private int a;

    public Bar()
    {
    }

    #region Implementation of ISerializable
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("a", a);
        info.AddValue("value1", value1);
        info.AddValue("value2", value2);
    }

    protected Bar(SerializationInfo info,StreamingContext context)
    {
        a = info.GetInt32("a");
        value1 = (Guid)info.GetValue("value1", typeof(Guid));
        value2 = info.GetDecimal("value2");
    }
    #endregion
}