Are methods also serialized along with the data me

2019-01-18 23:37发布

问题:

The title is obvious, I need to know if methods are serialized along with object instances in C#, I know that they don't in Java but I'm a little new to C#. If they don't, do I have to put the original class with the byte stream(serialized object) in one package when sending it to another PC? Can the original class be like a DLL file?

回答1:

No. The type information is serialized, along with state. In order to deserialize the data, your program will need to have access to the assemblies containing the types (including methods).



回答2:

It may be easier to understand if you've learned C. A class like

class C
{
    private int _m;
    private int _n;

    int Meth(int p)
    {
       return _m + _n + p;
    }
}

is essentially syntactic sugar for

typedef struct
{
   int _m;
   int _n;
   // NO function pointers necessary
} C;

void C_Meth(C* obj, int p)
{
   return obj->_m + obj->_n + p;
}

This is essentially how non-virtual methods are implemented in object-oriented languages. The important thing here is that methods are not part of the instance data.



回答3:

Methods aren't serialized.

I don't know about your scenario, but putting in a library (assembly / dll) and using that in the other end to deserialize gets you all.

Ps. you probably should create some ask some more questions with the factors involved in your scenario. If you are intending to dynamically send & run the code, you can create awful security consequences.



回答4:

I was confused when .NET first came up with serialization. I think it came from the fact that most books and guides mention that it allows you to serialize your 'objects' as XML and move them around, the fact is that you are actually hydrating the values of your object so you can dehydrate them latter. at no point your are saving your whole object to disk since that would require the dll and is not contained in the XML file.