如何检查如果对象是在C#序列化 [英] How to check if an object is serializable in C#

查看:107
本文介绍了如何检查如果对象是在C#序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找一个简单的方法来检查,如果在C#中的对象是可序列化。

I am looking for an easy way to check if an object in C# is serializable.

我们知道你让一个对象序列化或者通过实施的 ISerializable的的界面或放置的 [Serializable接口] 的在班上名列前茅。

As we know you make an object serializable by either implementing the ISerializable interface or by placing the [Serializable] at the top of the class.

我所寻找的是一个快速的方法来检查这一点,而不必以反映类来获得它的属性。该界面将使用快一个的的声明。

What I am looking for is a quick way to check this without having to reflect the class to get it's attributes. The interface would be quick using an is statement.

使用@ Flard的建议,这是code,我想出了,尖叫声是有一个更好的办法。

Using @Flard's suggestion this is the code that I have come up with, scream is there is a better way.

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

甚至更好刚刚得到的对象的类型,然后使用IsSerializable属性的类型:

Or even better just get the type of the object and then use the IsSerializable property on the type:

typeof(T).IsSerializable

记住尽管这这似乎才刚刚我们正在处理如果类包含你可能要检查他们全部或尝试和序列化,并等待错误,@pb指出了其他类的类。

Remember though this this seems to only just the class that we are dealing with if the class contains other classes you probably want to check them all or try and serialize and wait for errors as @pb pointed out.

推荐答案

您有一个可爱的财产键入类名为 IsSerializable

You have a lovely property on the Type class called IsSerializable.

这篇关于如何检查如果对象是在C#序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆