在使用 ISerializable
和 DataContractSerializer
时,如果要阻止序列化程序输出类型信息,可以使用以下方法:
DataContract
属性来定义数据协定。DataMember
属性来标记需要序列化的成员。DataContract
属性中,将 IsReference
设置为 true
。示例代码如下:
[DataContract(IsReference = true)]
public class MyClass : ISerializable
{
[DataMember]
public int MyProperty { get; set; }
public MyClass(SerializationInfo info, StreamingContext context)
{
MyProperty = info.GetInt32("MyProperty");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("MyProperty", MyProperty);
}
}
在这个示例中,我们使用 DataContract
属性来定义数据协定,并将 IsReference
设置为 true
。我们还使用 DataMember
属性来标记需要序列化的成员。在 GetObjectData
方法中,我们将 MyProperty
的值添加到 SerializationInfo
对象中。在 MyClass
的构造函数中,我们从 SerializationInfo
对象中获取 MyProperty
的值。
这样,在序列化和反序列化时,序列化程序将不会输出类型信息。
领取专属 10元无门槛券
手把手带您无忧上云