How to exclude specific types from serialization?

旧时模样 提交于 2019-12-06 21:10:55

问题


I run sgen against my assembly with a metric ton of types. I want to exclude 2 types from serialization. I don't seem to be able to find a way to do it.

I see that sgen has a /type switch to specify a specific type, but nothing to exclude a specific type.

Is there a way to exclude specific types from serialization?


回答1:


Apart from putting the types you wish to exclude in a different assembly, you cannot exclude types from the serializer generation.

Update

Other posters have come up with additional possibilities to exclude specific types, with varying applicability based on your use case.




回答2:


You can try changing the access of the classes you want to exclude from Xml Serialization by marking the class as internal, then sgen.exe should skip that class.

internal class NotToBeSerialized
{
    ...
}



回答3:


To prevent the class being included in sgen processing, ensure it doesn't have a parameterless constructor.

As explained by the answer to this question Why XML-Serializable class need a parameterless constructor, serialization requires a parameter less constructor, of any permission level, to work. Making the paramaterless constructor private isn't sufficient, to exclude if from sgen processing.




回答4:


Not sure if you are looking for this but you can exclude your own classes from serialization by mentioning [NonSerialized] before class definition. So if you want to exclude a specific type you will have to inherit from it and create your own class

[NonSerialized]
public class Point
{
    public int x, y;
}


来源:https://stackoverflow.com/questions/11569766/how-to-exclude-specific-types-from-serialization

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