C#如何判断一个对象是否可序列化 [英] How to check if an object is serializable in C#

查看:42
本文介绍了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.

我正在寻找的是一种快速检查这一点的方法,而不必反映类来获取其属性.使用 is 语句,界面会很快.

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 的建议,这是我想出的代码,尖叫有没有更好的方法.

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.

推荐答案

您在 Type 类中有一个可爱的属性,名为 IsSerializable.

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

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

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