如何确定是否所有的对象都是可序列化在一个给定的命名空间?都是、有的、对象、序列化

2023-09-03 04:09:04 作者:风月倦怠

一些背景:我们要求所有我们的DTO的对象是可序列化,使它们可以存储在会话或缓存

Some background: We require all of our DTO objects to be serializable so that they can be stored in session or cached.

你可以想像,这是非常恼人而且容易出错...是否有任何自动化的方式(最好作为构建过程的一部分),使用Visual Studio 2010,以确保命名空间的所有类都标有[ Serializable]属性?

As you can imagine, this is extremely annoying and prone to error... is there any automated way (ideally as part of the build process) using Visual Studio 2010 to ensure that all classes in a namespace are marked with the [Serializable] attribute?

推荐答案

您无法找到所有可能的类名称空间 - 但你的可以的发现的所有类特定组件内的 的具有指定的命名空间,并检查这些。

You can't find all possible classes in a namespace - but you can find all classes within a given assembly which have the specified namespace, and check those.

string dtoNamespace = ...;
Assembly assembly = ...;
var badClasses = assembly.GetTypes()
                         .Where(t => t.Namespace == dtoNamespace)
                         .Where(t => t.IsPublic) // You might want this
                         .Where(t => !t.IsDefined(typeof(SerializableAttribute),
                                     false);

断言, badClasses 为空,以任何你想要的方式:)

Assert that badClasses is empty in whatever way you want :)

编辑:正如意见中, IsSerializable 属性是有点儿方便在这里:)

As mentioned in the comments, the IsSerializable property is kinda handy here :)