Reflection and serialization

Source: Internet
Author: User


For reflection and serialization is a more in-depth knowledge general programming does not need to use especially reflection but it is a very helpful function for the people who need it.
Here's a brief introduction to reflection and serialization I'm not using the terminology in MSDN, or a formal explanation, but it's not going to be a mistake, so if you're vague about these two concepts, let's check out the MSDN explanations.

When do you want to use these two technologies?
Need to know the information structure Class attribute member variable of an object ... And so on, and so on and so on. Reflection will be able to provide you with the ability to interpret reflection as analytic reflection can parse almost all the information in an assembly (including object modules, etc.) in theory. NET schema program, and reflects external information. NET program is also possible not just to process objects simply remember to be an assembly.

Serialization is the process of rewriting an object into some sort of information format and storing it on a piece of media, of course, the format of some kind of information is to be restored. This is deserialization.

Let's see how reflection is going to work. Yes, I think so. Load an assembly and then use the class that it provides to manipulate the loaded assembly to get different information based on different classes.
The class that operates it is very rich, so you can almost get all the information you want. All classes and specific classes are available in MSDN too much knowledge to reflect so here I'll just use the PropertyInfo class action to show you how to get the property information you want to load the assembly. Of course You can also use FieldInfo eventinfo and so on to get field and event information seems to lift a counter five or something you can do.

Suppose you now want to reflect the entire properties of an object (some sensitive properties may not be available). You got to get an object first, of course. If you want to reflect external programs assembly classes can help you implement or refer external programs to your program to do so. NET programs are the same.

We use the type class to get the types of objects
Type type = obj. GetType ();

Assuming that obj is your object, there's a lot of information stored in this type of object GetProperties method will return the public property of this type and it returns a propertyinfo[] type. There is a filter parameter in the GetProperties method that filters the data parameters according to the criteria you specify is BindingFlags enumeration type most commonly used is bindingflags.instance instance members bindingflags.public public members BindingFlags.NonPublic is not a public member.

propertyinfo[] Proinfo = type. GetProperties (BindingFlags.Instance | BindingFlags.Public);
This allows you to get all the public properties of this object type.

Traverse All Properties
foreach (PropertyInfo p in Proinfo)
{
Console.WriteLine (p.getvalue (obj, null);//value of this property
}

Oh, it's too easy, isn't it? Well, maybe it's not too complicated, but it's a lot of knowledge. The read attribute that I demonstrated is also just a part of the reflection property and more action on the property.

So it's easier to say that serialization is about reflecting and serializing. That is, if you need to serialize an object, the quickest way to do this is to reflect the object's serialization first, of course, if you just want to serialize some of the familiar information of the object, there is no need for reflection.

Serialization please do not just think of converting to a format it also needs to be stored to be deserialized. Microsoft offers three of them. Class BinaryFormatter binary format for serialization operations, SoapFormatter in SOAP format, XmlSerializer generate XML format These classes can be serialized and deserialized in fact they operate the same The function of the XmlSerializer class seems to be the weakest to judge whether an object can be serialized by using IsSerializable. Defines an object that can be serialized by adding the [Serializable] identity before the class. The ISerializable interface can customize the process of controlling serialization and deserialization.

The following serializes an instance of a MyObject class using the XmlSerializer class to process the generated XML file

[Serializable]
public class MyObject
{
public int N1;
public int n2;
Public String str;

Public MyObject ()
{
N1 = 1;
N2 = 3;
str = "Sfantasy";
}
}


private void MyW ()
{
MyObject x = new MyObject ();
FileStream f = new FileStream ("Myfilename.xml", FileMode.Create, FileAccess.Write, Fileshare.none);
XmlSerializer xmls = new XmlSerializer (X.gettype ());
Xmls. Serialize (f, X);
F.close ();
}

The resulting XML document is the following

<?xml version= "1.0"?>
<myobject xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd= "Http://www.w3.org/2001/XMLSchema" >
<n1>1</n1>
<n2>3</n2>
<str>sfantasy</str>
</MyObject>


Then deserialization can read the data in the XML file to change the data of the existing object

private void MyR ()
{
MyObject MyObject = new MyObject ();
myobject.n1 = 0;
Myobject.str = "X";
XmlSerializer xmls = new XmlSerializer (Myobject.gettype ());
FileStream f = new FileStream ("Myfilename.xml", FileMode.Open);
MyObject = (myObject) xmls. Deserialize (f);
F.close ();
}

You can see how simple it is to serialize a custom object ~ Yes, serialization is very simple. It's very simple to use at least three of these operations, and I did say that. I understand the serialization implications so it seems to me that you don't use any of these three action classes to write an object in any format to any file and then restore it again. Because it can also be called serialization.

When you use these three classes, remember to include the namespaces that contain them.
Using System.xml.serialization;//xmlserializer
Using System.runtime.serialization.formatters.binary;//binaryformatter
Using System.runtime.serialization.formatters.soap;//soapformatter


The following code is the implementation of the other two serialization operations classes

SoapFormatter formatter = new SoapFormatter ()//Can be replaced by BinaryFormatter
FileStream stream = new FileStream ("Myfilename.xml", FileMode.Create, FileAccess.Write, Fileshare.none);
Formatter. Serialize (stream, array);
Stream. Close ();

The example I provide is primarily a description of the serialization system type using the SoapFormatter class and implementing serialization of a system object is more complex than implementing a custom object. Sometimes we need to serialize a control object such as a TextBox and its type TextBox has this property ( or events and other) information is somewhat serializable or not deserialized (I mean using the three serialization classes provided by Microsoft) and using other methods to serialize all the information of an object, such as writing XML files manually. Built-in types and others have not joined [ Serializable] Identification can be used to determine whether an object can be serialized using the isserializable mentioned above and you cannot modify the definition of the system type so you need to skip the operation.

Serializing all Control sample code for a form



Reflection does not have detailed code in the example so here's a more complete reflection code from Microsoft. Believe that smart you look after ... There's no need to lift a counter five.

This program lists the
System.IO.BufferedStream class.
Using System;
Using System.IO;
Using System.Reflection;

Class ListMembers {
public static void Main (string[] args) {
Specifies the class.
Type t = typeof (System.IO.BufferedStream);
Console.WriteLine ("Listing All" (public and non public) of the {0} type, T);

Lists static fields.
FieldInfo [] fi = T.getfields (bindingflags.static |
BindingFlags.NonPublic | BindingFlags.Public);
Console.WriteLine ("//Static Fields");
Printmembers (FI);

Static Properties.
PropertyInfo [] pi = t.getproperties (bindingflags.static |
BindingFlags.NonPublic | BindingFlags.Public);
Console.WriteLine ("//Static Properties");
Printmembers (PI);

Static events.
EventInfo [] ei = t.getevents (bindingflags.static |
BindingFlags.NonPublic | BindingFlags.Public);
Console.WriteLine ("//Static Events");
Printmembers (EI);

Static methods.
MethodInfo [] mi = t.getmethods (bindingflags.static |
BindingFlags.NonPublic | BindingFlags.Public);
Console.WriteLine ("//Static Methods");
Printmembers (MI);

Constructors.
ConstructorInfo [] ci = t.getconstructors (bindingflags.instance |
BindingFlags.NonPublic | BindingFlags.Public);
Console.WriteLine ("//constructors");
Printmembers (CI);

Instance fields.
fi = T.getfields (bindingflags.instance | BindingFlags.NonPublic |
BindingFlags.Public);
Console.WriteLine ("//Instance Fields");
Printmembers (FI);

Instance properites.
Pi = t.getproperties (bindingflags.instance | BindingFlags.NonPublic |
BindingFlags.Public);
Console.WriteLine ("//Instance Properties");
Printmembers (PI);

Instance events.
ei = t.getevents (bindingflags.instance | BindingFlags.NonPublic |
BindingFlags.Public);
Console.WriteLine ("//Instance Events");
Printmembers (EI);

Instance methods.
Mi = t.getmethods (bindingflags.instance | BindingFlags.NonPublic
| BindingFlags.Public);
Console.WriteLine ("//Instance Methods");
Printmembers (MI);

Console.WriteLine ("/r/npress ENTER to exit.");
Console.read ();
}

public static void Printmembers (MemberInfo [] ms) {
foreach (MemberInfo m in ms) {
Console.WriteLine ("{0}{1}", "", m);
}
Console.WriteLine ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.