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

前端 未结 2 832
萌比男神i
萌比男神i 2021-01-14 04:37

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

As you can imagine, this is extremely annoying

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-14 04:46

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

提交回复
热议问题