How to check if an object is serializable in C#

后端 未结 9 2059
太阳男子
太阳男子 2020-12-04 17:35

I am looking for an easy way to check if an object in C# is serializable.

As we know you make an object serializable by either implementing the ISerializable

相关标签:
9条回答
  • 2020-12-04 17:59

    You have a lovely property on the Type class called IsSerializable.

    0 讨论(0)
  • 2020-12-04 17:59
    Attribute.IsDefined(typeof (YourClass), typeof (SerializableAttribute));
    

    Probably involves reflection underwater, but the most simple way?

    0 讨论(0)
  • 2020-12-04 18:01

    You're going to have to check all types in the graph of objects being serialized for the serializable attribute. The easiest way is to try to serialize the object and catch the exception. (But that's not the cleanest solution). Type.IsSerializable and checking for the serializalbe attribute don't take the graph into account.

    Sample

    [Serializable]
    public class A
    {
        public B B = new B();
    }
    
    public class B
    {
       public string a = "b";
    }
    
    [Serializable]
    public class C
    {
        public D D = new D();
    }
    
    [Serializable]
    public class D
    {
        public string d = "D";
    }
    
    
    class Program
    {
        static void Main(string[] args)
        {
    
            var a = typeof(A);
    
            var aa = new A();
    
            Console.WriteLine("A: {0}", a.IsSerializable);  // true (WRONG!)
    
            var c = typeof(C);
    
            Console.WriteLine("C: {0}", c.IsSerializable); //true
    
            var form = new BinaryFormatter();
            // throws
            form.Serialize(new MemoryStream(), aa);
        }
    }
    
    0 讨论(0)
提交回复
热议问题