Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- MyComplexObject dto = new MyComplexObject();
- MemoryStream mem = new MemoryStream();
- BinaryFormatter b = new BinaryFormatter();
- try
- {
- b.Serialize(mem, dto);
- }
- catch (Exception ex)
- {
- Assert.Fail(ex.Message);
- }
- public static Stream Serialize(object source)
- {
- IFormatter formatter = new BinaryFormatter();
- Stream stream = new MemoryStream();
- formatter.Serialize(stream, source);
- return stream;
- }
- public static T Deserialize<T>(Stream stream)
- {
- IFormatter formatter = new BinaryFormatter();
- stream.Position = 0;
- return (T)formatter.Deserialize(stream);
- }
- public static T Clone<T>(object source)
- {
- return Deserialize<T>(Serialize(source));
- }
- [Serializable]
- class Foo {
- public Bar MyBar { get; set; }
- }
- [Serializable]
- class Bar {
- int x;
- }
- class DerivedBar {
- }
- public void TestSerializeFoo() {
- Serialize(new Foo()); // OK
- Serialize(new Foo() { MyBar = new Bar() }; // OK
- Serialize(new Foo() { MyBar = new DerivedBar() }; // Boom
- }
- private static void AssertThatTypeAndPropertiesAreSerializable(Type type)
- {
- // base case
- if (type.IsValueType || type == typeof(string)) return;
- Assert.IsTrue(type.IsSerializable, type + " must be marked [Serializable]");
- foreach (var propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
- {
- if (propertyInfo.PropertyType.IsGenericType)
- {
- foreach (var genericArgument in propertyInfo.PropertyType.GetGenericArguments())
- {
- if (genericArgument == type) continue; // base case for circularly referenced properties
- AssertThatTypeAndPropertiesAreSerializable(genericArgument);
- }
- }
- else if (propertyInfo.GetType() != type) // base case for circularly referenced properties
- AssertThatTypeAndPropertiesAreSerializable(propertyInfo.PropertyType);
- }
- }
Add Comment
Please, Sign In to add comment