How to check if an object is serializable in C#

后端 未结 9 2068
太阳男子
太阳男子 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 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);
        }
    }
    

提交回复
热议问题