部分或全部对象序列(partial or full object serialization)

2019-10-30 11:12发布

请看下面的Student确定指标:

public class Student
{
    public Guid Id {get; set;}
    public String FirstName {get; set;}
    public String LastName { get; set; }
}

使用C#序列化的属性,你怎么能适用两种不同的序列化配置?

当对象被传递给DataContractSerializer ,用户可以指定“idOnly”(局部的)或“完全”序列化。

我有两个运行时使用情况:

  1. 只有序列化的GUID
  2. 对象的完全序列化。

Answer 1:

我不知道什么样的系列化你在说什么。 但是,如果你使用的BinaryFormatter,要走的路是使学生类实现ISerializable。

然后,你可以这样做:

public void GetObjectData(SerializationInfo info, StreamingContext context)
{
  info.AddValue("Id", Id);

  if (SomeCondition)
  {
    info.AddValue("FirstName", FirstName);
    info.AddValue("LastName", LastName);
  }
}

凡SomeCondition可以使用一个静态(或线程静态)变量或里面的StreamingContext的一些信息。



Answer 2:

OK,删除答案XmlSerializer ,因为你使用DataContractSerializer

你可以做到这一点的方法之一DataContractSerializer是用替代。 代理项基本上是你的“真实”类中的一个交换的序列化的同时,反序列化和创建模式的替代类。 您可以使用这种伎俩来取代你的全职Student用一个简单的类StudentId在一些国家因类(如) ThreadStatic指示全部或部分学生是否被序列化状态变量。 (我用ThreadStatic的情况下,你可能有多个线程并行串行数据。)

因此,你的Student班会变成这样的事情:

[DataContract()]
public class Student
{
    [DataMember]
    public Guid Id { get; set; }
    [DataMember]
    public String FirstName { get; set; }
    [DataMember]
    public String LastName { get; set; }
}

[DataContract()]
public class StudentId
{
    [DataMember]
    public Guid Id { get; set; }
}

然后你的全局标志:

public static class SerializationFlags
{
    [ThreadStatic]
    static bool studentGuidOnly;

    public static bool StudentGuidOnly 
    {
        get { return studentGuidOnly; }
        set { studentGuidOnly = value; }
    }
}

接下来,您必须创建一个IDataContractSurrogate类告诉DataContractSerializer做出什么样的替代品。 在这个例子中,你将有条件地替换Student当只有ID为所需。 既然你只是做序列,而反序列化或模式的产生,大多数方法可以保持未实现:

public class StudentSurrogate : IDataContractSurrogate
{
    #region IDataContractSurrogate Members

    public object GetCustomDataToExport(Type clrType, Type dataContractType)
    {
        throw new NotImplementedException();
    }

    public object GetCustomDataToExport(System.Reflection.MemberInfo memberInfo, Type dataContractType)
    {
        throw new NotImplementedException();
    }

    public Type GetDataContractType(Type type)
    {
        if (type == typeof(Student) && SerializationFlags.StudentGuidOnly)
        {
            return typeof(StudentId);
        }
        return type;
    }

    public object GetDeserializedObject(object obj, Type targetType)
    {
        throw new NotImplementedException();
    }

    public void GetKnownCustomDataTypes(System.Collections.ObjectModel.Collection<Type> customDataTypes)
    {
        throw new NotImplementedException();
    }

    public object GetObjectToSerialize(object obj, Type targetType)
    {
        if (obj != null)
        {
            var type = obj.GetType();
            if (type == typeof(Student) && SerializationFlags.StudentGuidOnly)
            {
                var surrogate = new StudentId
                {
                    Id = ((Student)obj).Id,
                };
                return surrogate;
            }
        }
        return obj;
    }

    public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
    {
        throw new NotImplementedException();
    }

    public System.CodeDom.CodeTypeDeclaration ProcessImportedType(System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit)
    {
        throw new NotImplementedException();
    }

    #endregion
}

最后,这里是如何使用它的例子:

public static class DataContractSerializerHelper
{
    private static MemoryStream GenerateStreamFromString(string value)
    {
        return new MemoryStream(Encoding.Unicode.GetBytes(value ?? ""));
    }

    public static string GetXml<T>(T obj, DataContractSerializer serializer) where T : class
    {
        using (var textWriter = new StringWriter())
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = "    "; // The indentation used in the test string.
            using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
            {
                serializer.WriteObject(xmlWriter, obj);
            }
            return textWriter.ToString();
        }
    }

    public static string GetXml<T>(T obj) where T : class
    {
        DataContractSerializer serializer = new DataContractSerializer(typeof(T));
        return GetXml(obj, serializer);
    }
}

public static class SurrogateTest
{
    public static void Test()
    {
        Student kid = new Student();
        kid.Id = Guid.NewGuid();
        kid.FirstName = "foo";
        kid.LastName = "bar";

        DataContractSerializer dcs = new DataContractSerializer(
            typeof(Student),
            new Type [] { typeof(StudentId) },
            Int32.MaxValue,
            false, true, new StudentSurrogate());

        SerializationFlags.StudentGuidOnly = false;

        string xml1 = DataContractSerializerHelper.GetXml(kid, dcs);

        SerializationFlags.StudentGuidOnly = true;

        string xml2 = DataContractSerializerHelper.GetXml(kid, dcs);
     }
}

在这个测试用例,XML1是

<?xml version="1.0" encoding="utf-16"?>
<Student xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
    <FirstName z:Id="2">foo</FirstName>
    <Id>fa98b508-2fe9-4a09-b551-ba2ed1f70b70</Id>
    <LastName z:Id="3">bar</LastName>
</Student>

和XML2是

<?xml version="1.0" encoding="utf-16"?>
<Student xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="1" xmlns="" i:type="StudentId" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
    <Id>fa98b508-2fe9-4a09-b551-ba2ed1f70b70</Id>
</Student>

这是你所追求的。 最后,需要注意的是,虽然我的测试案例连载Student作为一个顶级对象,如果它嵌套一些类的对象图深处会发生更换。

再如,在这里看到: http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/14/wcf-extensibility-serialization-surrogates.aspx



文章来源: partial or full object serialization