How to check if an object is serializable in C#

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

    The exception object might be serializable , but using an other exception which is not. This is what I just had with WCF System.ServiceModel.FaultException: FaultException is serializable but ExceptionDetail is not!

    So I am using the following:

    // Check if the exception is serializable and also the specific ones if generic
    var exceptionType = ex.GetType();
    var allSerializable = exceptionType.IsSerializable;
    if (exceptionType.IsGenericType)
        {
            Type[] typeArguments = exceptionType.GetGenericArguments();
            allSerializable = typeArguments.Aggregate(allSerializable, (current, tParam) => current & tParam.IsSerializable);
        }
     if (!allSerializable)
        {
            // Create a new Exception for not serializable exceptions!
            ex = new Exception(ex.Message);
        }
    

提交回复
热议问题