How to determine if all objects are serializable in a given namespace?

北城以北 提交于 2019-12-01 10:31:36

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);

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

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

One tool you might like to think about, that is easily integrated into your build, is NDepend. This lets you run various code metrics, which you can then use to warn/fail your build.

In CQL (the built in query language in NDepend), you would write something like:

WARN IF Count > 0 IN SELECT TYPES FROM NAMESPACES "namespace" WHERE !IsSerializable  

Obviously this will only find namespaces for types that are included in assemblies within your solution, but I assume that's what you mean.

NDepend can be run automatically as part of your build within VS, or on a seperate build server. It can also be run as a standalone application.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!