Created
September 5, 2017 14:51
-
-
Save CXuesong/a29e8c126db96343e5948d67eb6010db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Linq; | |
using System.Reflection; | |
using System.Runtime.Serialization; | |
using System.Runtime.Serialization.Formatters; | |
using System.Runtime.Serialization.Formatters.Binary; | |
using System.Text; | |
namespace CoreSerializationTest | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var formatter = new BinaryFormatter(new MySurrogateSelector(), new StreamingContext()); | |
var t = Laundry(typeof(string), formatter); | |
Console.WriteLine("Deserialized: {0}", t); | |
} | |
private static T Laundry<T>(T graph, IFormatter formatter) | |
{ | |
using (var st = new MemoryStream()) | |
{ | |
formatter.Serialize(st, graph); | |
st.Position = 0; | |
Console.WriteLine(Encoding.ASCII.GetString(st.ToArray())); | |
return (T)formatter.Deserialize(st); | |
} | |
} | |
} | |
public class MySurrogateSelector : ISurrogateSelector | |
{ | |
public void ChainSelector(ISurrogateSelector selector) | |
{ | |
throw new NotImplementedException(); | |
} | |
public ISurrogateSelector GetNextSelector() | |
{ | |
return null; | |
} | |
public ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector) | |
{ | |
Console.WriteLine("Test for surrogate: " + type); | |
if (typeof(Type).IsAssignableFrom(type)) | |
{ | |
selector = this; | |
return new TypeSerializationSurrogate(); | |
} | |
selector = null; | |
return null; | |
} | |
} | |
public sealed class TypeSerializationSurrogate : ISerializationSurrogate | |
{ | |
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) | |
{ | |
var type = (Type)obj; | |
info.AddValue("AssemblyName", type.Assembly.FullName); | |
info.AddValue("FullName", type.FullName); | |
} | |
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, | |
ISurrogateSelector selector) | |
{ | |
var assemblyName = info.GetString("AssemblyName"); | |
var fullName = info.GetString("FullName"); | |
var assembly = Assembly.Load(assemblyName); | |
return assembly.GetType(fullName, true); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment