確認方法の場合、オブジェクトが直列化可能クライアントまで、フルのC#
-
09-06-2019 - |
質問
もっと簡単にチェックがオブジェクトのC#では直列化可能です。
ご存知のようにしているオブジェクトの直列化可能のいずれかの実施 ISerializable インタフェースを置いて [直列化可能] 上部のクラスです。
私の見るには、迅速にチェックせずにクラスを取得します。のコントロールする迅速使用 は ます。
使用@Flardの提案このコードしていくとの声があります。
private static bool IsSerializable(T obj)
{
return ((obj is ISerializable) || (Attribute.IsDefined(typeof (T), typeof (SerializableAttribute))));
}
もったオブジェクトの型を使用してIsSerializable財産の種類:
typeof(T).IsSerializable
覚えていこうばかりであるクラスを取り扱っておりますが、クラスを含むその他のクラスだチェックしようとserialize待ち誤差を@pbを指摘しなければなりません。
解決
お持ちの愛らしの物件で Type
クラスと呼ばれ IsSerializable
.
他のヒント
いかチェックすべての種類のグラフブジェクトが直列化されたため、直列化可能属性をもつ。最も簡単な方法を試してみるのserializeのオブジェクトの例外です。(実際にはそうではありません美しいです。タイプです。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);
}
}
ことを義務付けられている,する必要がある場合もあり更新されます。純3.5+.タイプです。IsSerializableい場合はfalseを返す場合にクラスを使用しDataContractの属性。ここでは、スニペットを使っていな臭いを知:)
public static bool IsSerializable(this object obj)
{
Type t = obj.GetType();
return Attribute.IsDefined(t, typeof(DataContractAttribute)) || t.IsSerializable || (obj is IXmlSerializable)
}
使用タイプです。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
していくとともに、デジタルカメを判定するための具体的なインスタンスの型の直列化可能なので通常はまず、全ての場合がございます。
Attribute.IsDefined(typeof (YourClass), typeof (SerializableAttribute));
れる反射、水中でも最も簡単。
この3.5バリエーション可能なすべてのクラスを拡張方法です。
public static bool IsSerializable(this object obj)
{
if (obj is ISerializable)
return true;
return Attribute.IsDefined(obj.GetType(), typeof(SerializableAttribute));
}
私の答えはこの質問とその答え こちらの やれんの一覧を取得しタイプなの直列化可能です。そのように簡単に知るものをマークです。
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しています。が良いということ以上に渡す場合、空のリストを再帰的方法です。誰かに訂正いた場合です。
の例外オブジェクトが直列化可能な使用の例外ではない。そして、自分の書いた文章だったとWCFます。ServiceModel.FaultException:FaultExceptionは直列化可能で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);
}
私の溶液は、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