Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

serialization - C# serialize private class member

class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}

Simple question yet it seems like a big mess when trying to answer it.
Everyone suggest to use public getter/setter but my app is too big and making a getter/setter for each member would just cause maintainability issues.

Am I forced to create a custom serialization here or is there a magic attribute for such members?
How do I serialize private class members?

Edit #1:
Ok everyone, sorry for the unclarity, I was a bit upset when I wrote this question, it was several hours after trying to find the solution.
Anyway, here are more facts:
1. I'm trying to XML serialize this class. Currently I'm using System.Xml.Serialization.XmlSerializer.
2. I'm serializing into XML to have version compatibility, which as far as I understand binary doesn't offer me that.
3.I was hoping that there's a certain attribute like:

class Person
{
    public string m_name;
    [SerializeThat(ElementName="Age")]
    private int m_age; // << how do I serialize the darn little rat?
}

OR (continue of fact #3) an attribute that goes on the class which would look like:

[Serializable(DoPrivate = true, DoProtected = true)]
class Person
{
    public string m_name;
    private int m_age; // << how do I serialize the darn little rat?
}

Now, what can I do to achieve it?

question from:https://stackoverflow.com/questions/4314982/c-sharp-serialize-private-class-member

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Going on the assumption of a typo, I'd like to redirect you to this SO article where the solution is to use a DataContractSerializer instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...