2

How can deserialize one class to another class like this:

var ser = SerializedObject(b);// read from Database!

var des = DeSerializeAnObject(ser, typeof(BaseClass));

BaseClass baseclass = (BaseClass)des;

baseclass.Hello();

2 Answers2

1

Are you sure it's really serialization/deserialization you're after? Sounds to me like what you're looking for is code to map (ie copy selected or all properties) one object to another.

Have a look at the AutoMapper Getting Started Guide.

In following with your example you could do something like this

BaseClass baseClass = Mapper.Map<OtherClass, BaseClass>(b);

I'm also somewhat confused with your choice of class names in your example. If "BaseClass" really is a base class of OtherClass then you'd just do a cast instead but I'm going to guess that's not the case.

Markus Olsson
  • 22,402
  • 9
  • 55
  • 62
  • suppose I don't have Other Class,(only serialized class is in database). I want Execute Hello() from serialized object.Excuse me, my english is bad. – Ahmad Ahmadi Dec 18 '11 at 12:09
  • @AhmadAhmadi Do you mean that some other process/system is serializing objects of types unknown to you into a database and you wish to deserialize them? – Markus Olsson Dec 18 '11 at 12:13
  • Yes,I must deserialize them and execute Methods. – Ahmad Ahmadi Dec 18 '11 at 12:15
  • 1
    @AhmadAhmadi then you're out of luck I'm afraid. Serialization will only persist the instance fields of a serialized instance, not the method bodies. The data that you have in your database simply doesn't contain enough information. You need access (at runtime) to the class definition to be able to deserialize your data into anything useful. – Markus Olsson Dec 18 '11 at 12:19
-1

a deserialize sample is like ...

    public BaseClass DeSerializeAnObject(BaseClass bc)
    {
        if (bc == null) return bc;

        IFormatter formatter = new BinaryFormatter();
        using (Stream stream = new MemoryStream())
        {
            formatter.Serialize(stream, bc);
            stream.Seek(0, SeekOrigin.Begin);
            return (BaseClass)formatter.Deserialize(stream);
        }
    }
shenhengbin
  • 4,236
  • 1
  • 24
  • 33