How to check if an object is serializable in C#

后端 未结 9 2069
太阳男子
太阳男子 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:53

    Use Type.IsSerializable as others have pointed out.

    It's probably not worth attempting to reflect and check if all members in the object graph are serializable.

    A member could be declared as a serializable type, but in fact be instantiated as a derived type that is not serializable, as in the following contrived example:

    [Serializable]
    public class MyClass
    {
       public Exception TheException; // serializable
    }
    
    public class MyNonSerializableException : Exception
    {
    ...
    }
    
    ...
    MyClass myClass = new MyClass();
    myClass.TheException = new MyNonSerializableException();
    // myClass now has a non-serializable member
    

    Therefore, even if you determine that a specific instance of your type is serializable, you can't in general be sure this will be true of all instances.

提交回复
热议问题