Check if a class can be serialized

I want to create a general method for the serizlize class for text (to be used as part of a network component) The method should look something like this:

public string SerializeToText<T>(T DataToSerialize);

The contents of the method would simply serialize the xml, and I can do it. I want to know if I can check if T: can be serialized, preferably at compile time, but otherwise at runtime.

+3
source share
3 answers

The most reliable way to check and see if a serializable object serializable is to serialize it. If it succeeds, then the object was serializable; if it throws it, then it was not serializable.

, , . , , .

[Serialiable] 
class Foo { 
  public object Field;
}
class Bar { }

var value = new Foo() { Field1 = 42; } // value is serializable
value.Field1 = new Bar();  // value is no longer serializable

, , . .

+5

, . # , , , unserializable .

, , , , , .

, . , , , object.

, .NET, , . , , . SerializeToText .

interface ICanSerialize
{
    void Serialize(ISerializeMedium m);
}

interface ISerializeMedium
{
    void Serialize(string name, ref int value);
    void Serialize(string name, ref bool value);
    void Serialize(string name, ref string value);
    void Serialize<T>(string name, ref T value) where T : ICanSerialize;
    void Serialize<T>(string name, ref ICollection<T> value) where T : ICanSerialize;

    // etc.
}

:

class C : ICanSerialize
{
    string _firstName;
    bool _happy;

    public void Serialize(ISerializeMedium m)
    {
        m.Serialize("firstName", ref _firstName);
        m.Serialize("happy", ref _happy);
    }
}

ISerializeMedium. , , , .

, .

0

Are you referring to this?

if (typeof(T).IsSerializable)
-1
source

Source: https://habr.com/ru/post/1736221/


All Articles