How to check if an object is serializable in C#

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

    This is an old question, that may need to be updated for .NET 3.5+. Type.IsSerializable can actually return false if the class uses the DataContract attribute. Here is a snippet i use, if it stinks, let me know :)

    public static bool IsSerializable(this object obj)
    {
        Type t = obj.GetType();
    
         return  Attribute.IsDefined(t, typeof(DataContractAttribute)) || t.IsSerializable || (obj is IXmlSerializable)
    
    }
    

提交回复
热议问题