ZeroFormatter icon indicating copy to clipboard operation
ZeroFormatter copied to clipboard

Serialization does not work when parameter is of type object

Open grendo opened this issue 7 years ago • 1 comments

I have a cache class where a method takes a parameter of type object, (note I can not change the parameter to be a generic type). I found a strange behavior as show in the test below where zero formatter crashes because object is not registerd.

        [ZeroFormattable]
        public class MyDateTest
        {
            [Index(0)]
            public virtual DateTime TheDate { get;set; }
        }

        [Test]
        public void TestZeroFormatter()
        {
            var obj = new MyDateTest {TheDate = DateTime.Now};
            // works
            var bytes = ZeroFormatterSerializer.Serialize(obj);
            // crashes because the parameter is of type object
            var bytes2 = ZeroFormatterObject(obj);

        }

        private byte[] ZeroFormatterObject(object obj)
        {
            var bytes = ZeroFormatterSerializer.Serialize(obj);
            return bytes;
        }

grendo avatar Apr 03 '17 23:04 grendo

I got a work around by calling the ZeroFormatterSerializer<T>(T obj) via reflection with the correct type. Bit ugly but works for now

```
[ZeroFormattable]
    public class MyDateTest
    {
        [Index(0)]
        public virtual DateTime TheDate { get;set; }
    }

    [Test]
    public void TestZeroFormatter()
    {
        var obj = new MyDateTest {TheDate = DateTime.Now};
        // works
        var bytes = ZeroFormatterSerializer.Serialize(obj);
        // now works as zeroformatter is invoked via calling generic serialize method via refelection with correct type
        var bytes2 = ZeroFormatterObject(obj);

        var deserialized = ZeroFormatterSerializer.Deserialize<MyDateTest>(bytes2);

    }

    private byte[] ZeroFormatterObject(object obj)
    {
        var objType = obj.GetType();
        var zeroFormatterType = typeof(ZeroFormatterSerializer);
        var genericMethod = zeroFormatterType.GetMethods().First(e => e.IsGenericMethod && e.Name == "Serialize" && e.GetParameters().Length == 1);
        var constructedGenericMethod = genericMethod.MakeGenericMethod(objType);
        var bytes = constructedGenericMethod.Invoke(null, new object[] {obj}) as byte[];
        return bytes;
    }

grendo avatar Apr 03 '17 23:04 grendo