96

C#のオブジェクトがシリアル化可能かどうかを確認する簡単な方法を探しています。

ご存知のとおり、 ISerializableインターフェイスを実装するか、[Serializable]をクラスの最上位に配置することで、オブジェクトをシリアライズ可能にします。

私が探しているのは、クラスを反映して属性を取得することなく、これをすばやく確認する方法です。isステートメントを使用すると、インターフェイスが高速になります。

@Flardの提案を使用して、これは私が思いついたコードです、悲鳴はより良い方法があります。

private static bool IsSerializable(T obj)
{
    return ((obj is ISerializable) || (Attribute.IsDefined(typeof (T), typeof (SerializableAttribute))));
}

または、オブジェクトの型を取得してから、その型でIsSerializableプロパティを使用することをお勧めします。

typeof(T).IsSerializable

これは、クラスに他のクラスが含まれている場合に処理しているクラスのみに見えることを覚えておいてください。おそらく、それらすべてをチェックするか、@ pbが指摘したように、シリアル化してエラーを待ちます。

4

9 に答える 9

121

Typeというクラスに素敵なプロパティがありますIsSerializable

于 2008-09-17T10:20:08.773 に答える
43

シリアル化されるオブジェクトのグラフで、シリアル化可能な属性のすべてのタイプを確認する必要があります。最も簡単な方法は、オブジェクトをシリアル化して例外をキャッチすることです。(しかし、それは最もクリーンな解決策ではありません)。Type.IsSerializableとserializalbe属性のチェックでは、グラフは考慮されません。

サンプル

[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);
    }
}
于 2008-09-17T10:13:30.863 に答える
18

これは古い質問で、.NET 3.5+ 用に更新する必要がある場合があります。クラスが DataContract 属性を使用している場合、Type.IsSerializable は実際には false を返すことがあります。これが私が使用するスニペットです。臭いがする場合はお知らせください:)

public static bool IsSerializable(this object obj)
{
    Type t = obj.GetType();

     return  Attribute.IsDefined(t, typeof(DataContractAttribute)) || t.IsSerializable || (obj is IXmlSerializable)

}
于 2010-10-27T21:22:32.553 に答える
9

他の人が指摘したように Type.IsSerializable を使用してください。

オブジェクト グラフ内のすべてのメンバーがシリアライズ可能かどうかを反映して確認しようとする価値はおそらくありません。

メンバーはシリアル化可能な型として宣言できますが、実際には、次の不自然な例のように、シリアル化できない派生型としてインスタンス化されます。

[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

したがって、型の特定のインスタンスがシリアル化可能であると判断した場合でも、一般に、これがすべてのインスタンスに当てはまるかどうかを確認することはできません。

于 2008-09-17T11:46:14.823 に答える
6
Attribute.IsDefined(typeof (YourClass), typeof (SerializableAttribute));

おそらく水中での反射が含まれますが、最も簡単な方法はありますか?

于 2008-09-17T10:12:21.523 に答える
5

これは、拡張メソッドを使用してすべてのクラスで使用できるようにする 3.5 のバリエーションです。

public static bool IsSerializable(this object obj)
{
    if (obj is ISerializable)
        return true;
    return Attribute.IsDefined(obj.GetType(), typeof(SerializableAttribute));
}
于 2008-09-17T10:29:15.540 に答える
2

この質問に対する回答とここでの回答を取得し、シリアル化できないタイプのリストを取得できるように修正しました。そうすれば、どれをマークするかを簡単に知ることができます。

    private static void NonSerializableTypesOfParentType(Type type, List<string> nonSerializableTypes)
    {
        // base case
        if (type.IsValueType || type == typeof(string)) return;

        if (!IsSerializable(type))
            nonSerializableTypes.Add(type.Name);

        foreach (var propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
        {
            if (propertyInfo.PropertyType.IsGenericType)
            {
                foreach (var genericArgument in propertyInfo.PropertyType.GetGenericArguments())
                {
                    if (genericArgument == type) continue; // base case for circularly referenced properties
                    NonSerializableTypesOfParentType(genericArgument, nonSerializableTypes);
                }
            }
            else if (propertyInfo.GetType() != type) // base case for circularly referenced properties
                NonSerializableTypesOfParentType(propertyInfo.PropertyType, nonSerializableTypes);
        }
    }

    private static bool IsSerializable(Type type)
    {
        return (Attribute.IsDefined(type, typeof(SerializableAttribute)));
        //return ((type is ISerializable) || (Attribute.IsDefined(type, typeof(SerializableAttribute))));
    }

そして、あなたはそれを呼び出します...

    List<string> nonSerializableTypes = new List<string>();
    NonSerializableTypesOfParentType(aType, nonSerializableTypes);

実行すると、nonSerializableTypes にリストが含まれます。空の List を再帰メソッドに渡すよりも、これを行うためのより良い方法があるかもしれません。もしそうなら、誰かが私を訂正してください。

于 2012-10-24T17:25:48.403 に答える
1

VB.NETでの私のソリューション:

オブジェクトの場合:

''' <summary>
''' Determines whether an object can be serialized.
''' </summary>
''' <param name="Object">The object.</param>
''' <returns><c>true</c> if object can be serialized; otherwise, <c>false</c>.</returns>
Private Function IsObjectSerializable(ByVal [Object] As Object,
                                      Optional ByVal SerializationFormat As SerializationFormat =
                                                                            SerializationFormat.Xml) As Boolean

    Dim Serializer As Object

    Using fs As New IO.MemoryStream

        Select Case SerializationFormat

            Case Data.SerializationFormat.Binary
                Serializer = New Runtime.Serialization.Formatters.Binary.BinaryFormatter()

            Case Data.SerializationFormat.Xml
                Serializer = New Xml.Serialization.XmlSerializer([Object].GetType)

            Case Else
                Throw New ArgumentException("Invalid SerializationFormat", SerializationFormat)

        End Select

        Try
            Serializer.Serialize(fs, [Object])
            Return True

        Catch ex As InvalidOperationException
            Return False

        End Try

    End Using ' fs As New MemoryStream

End Function

タイプの場合:

''' <summary>
''' Determines whether a Type can be serialized.
''' </summary>
''' <typeparam name="T"></typeparam>
''' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns>
Private Function IsTypeSerializable(Of T)() As Boolean

    Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))

End Function

''' <summary>
''' Determines whether a Type can be serialized.
''' </summary>
''' <typeparam name="T"></typeparam>
''' <param name="Type">The Type.</param>
''' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns>
Private Function IsTypeSerializable(Of T)(ByVal Type As T) As Boolean

    Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))

End Function
于 2014-08-02T15:24:33.817 に答える
0

例外オブジェクトは serializable である可能性がありますが、そうでない他の例外を使用しています。これは、私が WCF System.ServiceModel.FaultException: FaultException is serializable で持っていたものですが、ExceptionDetail はそうではありません!

だから私は以下を使用しています:

// 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);
    }
于 2011-05-06T14:43:20.537 に答える