foreach field in class ???

  • Thread starter Thread starter ORC
  • Start date Start date
O

ORC

I have a class with a lot of fields/variables that must be saved to a file
and loaded from a file. AFAIK the full framework has a serializing feature
but what about the compact framework? If there is something like a "foreach
field in class: save to file" - I think it would solve the problem - Any
help is highly appreciated

Thanks
Ole
 
Generally you do this by using Reflection to enumerate either fields (public
or/and nonpublic) or properties.
The more widely accepted approach is to use public read/write properties.
Each field that needs to be serialized is exposed via read/write property.
Then you walk the properties on a particular object and write the values to
the output stream


foreach( PropertyInfo pi in myObj.GetType().GetProperties() )
{
object val = pi.GetValue(myObj, new object[] {});
// Write val to the output stream
}

Reading from Stream is done similarly.
If you want a more fine-grained control over what should be serialized and
what should not, I suggest using custom attributes on the class properties
 
Thanks Alex,

C# and .NET is rather new to me so if anyone would help me with an example I
would be very glad. What I actually need is to write and read some
configuration settings in a file. I would therefore appreciate an example of
how to read and write this class from and to a config file:

public class Config
{
string Var1 = "default"; // default value of Var1
int Var2 = 6; // default value of Var1
}

Could the method be implemented inside the class itself, like having a
method e.g. called: SaveConfig and LoadConfig ??

Thanks
Ole


Alex Feinman said:
Generally you do this by using Reflection to enumerate either fields (public
or/and nonpublic) or properties.
The more widely accepted approach is to use public read/write properties.
Each field that needs to be serialized is exposed via read/write property.
Then you walk the properties on a particular object and write the values to
the output stream


foreach( PropertyInfo pi in myObj.GetType().GetProperties() )
{
object val = pi.GetValue(myObj, new object[] {});
// Write val to the output stream
}

Reading from Stream is done similarly.
If you want a more fine-grained control over what should be serialized and
what should not, I suggest using custom attributes on the class properties

--
Alex Feinman
---
Visit http://www.opennetcf.org
ORC said:
I have a class with a lot of fields/variables that must be saved to a file
and loaded from a file. AFAIK the full framework has a serializing feature
but what about the compact framework? If there is something like a
"foreach
field in class: save to file" - I think it would solve the problem - Any
help is highly appreciated

Thanks
Ole
 
Back
Top