Programming with ReflectionReflection's main purpose is to provide type information in execution. In .NET Framework, the Reflection is operated by Type objects. Among them, it is divided into two parts: First, provide information, such as public, sealed, etc. ) Returns the constructorInfo object or array, GetField (s) returns the fieldInfo object or array. For more information about Type class, see http://msdn.microsoft.com/library/chs/default.asp?url=/library/chs/cpref/html/frlrfsystemTypeMBerstopic.asp Dynamic InvokereFlection allows designers to dynamically call functions. You can call it through the INVOKE method of the MethodInfo object, or you can also call directly through Type's InvokeMember.
Namespace DesignPattern
{
///
/// ReflectionTest's summary description.
/// summary>
Public Class ReflectionTest: System.Web.ui.page
{
Private Void Page_Load (Object Sender, System.EventArgs E)
{
MyData MD = New MyData (10);
Object [] o = new object [] {1};
o [0] = 5;
TYPE T = TypeOf (myData); // Get the TYPE information of MyData
MethodInfo mi = T. GetMethod ("Zero");
Mi.invoke (MD, NULL); // Call MD ZERO through the INVOKE method of the MethodInfo object
Response.write (md.getnum ());
T.invokeMember ("setnum", bindingflags.invokeMethod, NULL, MD, O); // Setnum called MD via Type
Response.write (T. InvokeMember ("GetNum", BindingFlags.InvokeMethod, NULL, MD, NULL);
}
#Region web form designer generated code
Override protected void oninit (Eventargs E)
{
//
// Codegen: This call is necessary for the ASP.NET Web Form Designer.
//
InitializationComponent ();
Base.onit (E);
}
///
/// Designer supports the required method - do not use the code editor to modify
/// This method is content.
/// summary>
Private vidinitiRizeComponent ()
{
This.Load = New System.EventHandler (this.page_load);
}
#ndregion
}
// A simple class, has an int private member, public method has 0, assignment, and acquisition.
Public Class MyData
{
Private INT i;
Public MyData (INT A)
{
i = a;
}
Public void zero ()
{
i = 0;
}
Public void setnum (INT A)
{
i = a;
}
Public int getnum ()
{
Return I;
}
}
}
Don't forget the use system.reflection; Collection Collection refers to the container of a group of elements, and the concept is extended by the array. 1, IENUMERABLE interface. The object that implements this interface can use foreach. The IEnumerable interface is only predefined with a function getENUMERATOR, returns an IENUMERATOR object instance. The following is the code example:
Public Class Myenumerator: ienumerator
{
Private Int_index;
Private string [] _List;
Public myenumerator (string [] list)
{
_INDEX = -1;
_List = List;
}
Public void reset ()
{
_INDEX = -1;
}
Public Object Current
{
get
{
Return_List [_Dex];
}
}
Public bool movenext ()
{
_INDEX ;
IF (_index> = _ list.Length)
{
_INDEX = _List.Length-1;
Return False;
}
Return True;
}
}
Public class myenumerable: ienumerable
{
Private string [] _List;
Public myenumerable ()
{
_List = new string [3] {"1", "2", "3"};
}
Public ienumerator geteNumerator ()
{
Return new myenumerator (_list);
}
}
With the class that implements the Ienumerator and the IEnumerable interface, 123 can be output by the following code
Myenumerable me = new myenumerable ();
Foreach (String S in Me) Response.write (s);
2, the Icollection interface is the reinforced interface of Ienumerable
Public Interface iCollection: IEnumerable
{
INT count {get;}
Object syncroot {get;}
Bool issynchronized {get;}
Void CopyTo (Array Array, Int Index);
}
The class of the following code implements the iCollection interface.
Public Class MyCollection: Icollection
{
Private string [] _List;
Private Object _root;
Public mycollection ()
{
_List = new string [3] {"1", "2", "3"};
}
Public Bool Issynchronized
{
get
{
Return True;
}
}
Public Int Count
{
get
{
Return_List.Length;
}
}
Public void CopyTo (Array Array, Int Index)
{
_List.copyto (array, index);
}
Public Object Syncroot
{
get
{
Return _root;
}
}
Public ienumerator getenumerator () {
Return_List.GeteNumerator ();
}
}
3, the ILIST interface provides the ability to modify the COLLECTION internal elements. In fact it is a complex of the Ienumerable and Icollection interface. The prototype is as follows
Public Interface IList: iCollection, IEnumerable
{
Object this [int index] {get; set;}
Bool isreadonly {get;}
Bool isfixedsize {get;}
INT Add (Object Value);
Bool Contains; Object Value;
Void clear ();
INT INDEXOF (Object Value);
Void Insert (int index, object value);
Void Remove (Object Value);
Void Removeat (INT INDEX);
}
Here is a class that implements the IList interface.
Public class mylist: ilist
{
Private arraylist _list;
Public mylist ()
{
_List = new arraylist ();
}
#Region IList member
Public Bool IsReadonly
{
get
{
Return False;
}
}
Public Object this [int index]
{
get
{
Return_List [index];
}
set
{
_List [index] = value;
}
}
Public Void Removeat (int index)
{
_List.removeat (INDEX);
}
Public void insert (int index, object value)
{
_List.Insert (Index, Value);
}
Public Void Remove (Object Value)
{
_List.Remove (Value);
}
Public Bool Contains (Object Value)
{
Return_List.Contains (Value);
}
Public void clear ()
{
_List.clear ();
}
Public int indexof (Object Value)
{
Return_List.Indexof (Value);
}
Public Int Add (Object Value)
{
Return_List.Add (Value);
}
Public Bool IsFixedsize
{
get
{
Return False;
}
}
#ndregion
#Region Icollection member
Public Bool Issynchronized
{
get
{
Return_List.issynchronized;
}
}
Public Int Count
{
get
{
Return_List.count;
}
}
Public void CopyTo (Array Array, Int Index)
{
_List.copyto (array, index);
}
Public Object Syncroot
{
get
{
Return_List.syncroot;
}
}
#ndregion
#Region Ienumerable member
Public ienumerator geteNumerator ()
{
Return_List.GeteNumerator ();
}
#ndregion
}
4, the previous interface uses Object as the element type in the Collection, so all objects can be placed in Collection, but this design is too loose, easy to produce mix, sometimes a strong-type collection. For designers' demand for Strong-Type Collection, .NET Framework provides a basic class of CollectionBase. Below is a simple example, List in the code is a protected ilist in CollectionBase, which contains a list of elements in the CollectionBase instance. Public Class Int16Collection: CollectionBase {
Public INT16 this [int index] {
Get {
Return (INT16) List [index]);
}
SET {
List [Index] = Value;
}
}
Public int Add (INT16 VALUE) {
Return (List.Add (Value));
}
Public int indexof (INT16 VALUE) {
Return (list.indexof (value);
}
Public void INSERT (int index, int16 value) {
List.Insert (Index, Value);
}
Public void remove (INT16 VALUE) {
List.remove (Value);
}
Public Bool Contains (INT16 VALUE) {
Return (List.Contains (Value);
}
}
CodeDom It is the basic construction of program code in .NET Framework, which simulates the logic of the program code in an objective manner, and finally handed over the specific Code Provider object (E.G. CsharpCodeProvider) generate source code. CodeCompileUnit is CodeDom in a volumetric object. The CODENAMESPACE object can produce a NameSpace statement. CODETYPEDECLATION can be used to generate objects of the statement, can handle classes, enumerations, interfaces, and structures. CodeMverse, CodeMBerMethod, CodeMeMberProperty, and CodeMemevent can generate member variables, methods, properties, and events, respectively. Specifies the return value type by specifying the return value type and generates Return code by adding the CodeMethodReturnStateMent object. Add paramerters to specify the parameters passed by the method. The following is a sample code:
Using system;
Using system.collections;
Using system.componentmodel;
Using system.data;
Using system.drawing;
Using system.Web;
Using system.Web.SessionState;
Using system.Web.ui;
Using system.Web.ui.webcontrols;
Using system.Web.ui.htmlcontrols;
Using system.codedom;
Using system.codedom.compiler;
USING Microsoft.csharp;
Using system.io;
Namespace DesignPattern
{
///
/// CodeDomtest's summary description.
/// summary> public class codedomtest: System.Web.ui.page
{
Private Void Page_Load (Object Sender, System.EventArgs E)
{
// Create a root container object
CodeCompileUnit Unit = New CodeCompileUnit ();
// Create a Provider object that generates the source code
Codedomprovider provider = new csharpcodeProvider ();
// Create an object that generates Namespace
CODENAMESPACE CNS = New CodeNameSpace ("MyNameSpace");
// Create an object of NameSpace
CODENAMESPACEIMPORT CNSI = New CodeNameSpaceImport ("System");
Cns.imports.Add (CNSI);
// Create an object that generates class
CODETYPEDECLATION CTD = New CodeTypedeclaration ("MyClass");
CTD.Isclass = true;
// Create a member function
Codememberfield CMF = New CodeMemberfield (Typeof (Int), "One");
CTD.Members.Add (CMF);
// Create a class method
CodeMBerMethod Cmm = new codememberMethod ();
Cmm.name = "getnum";
CMM.Returntype = New CodePereference (TypeOf (int));
CMM.Attributes = Memblic;
CMM.Statements.Add (New CodeMethodReturnstatement (New CodeargumentReferenceExpression ("One")))
CTD.Members.Add (cmm);
CNS.TYPES.ADD (CTD);
Unit.NameSpaces.Add (CNS);
// Generate the code to d: /test.cs
ICodeGenerator gen = provider.creategenerator ();
Streamwriter SW = New StreamWriter ("D: //Test.cs", False);
Gen.generatecodefromCompileunit (Unit, SW, New CodegeneratorOptions ());
SW.CLOSE ();
}
#Region web form designer generated code
Override protected void oninit (Eventargs E)
{
//
// Codegen: This call is necessary for the ASP.NET Web Form Designer.
//
InitializationComponent ();
Base.onit (E);
}
///
/// Designer supports the required method - do not use the code editor to modify
/// This method is content.
/// summary>
Private vidinitiRizeComponent ()
{
This.Load = New System.EventHandler (this.page_load);
}
#ndregion
}
}
The generated Test.cs is as follows:
Namespace mynamespace {
Using system;
Public class myclass {
PRIVATE INT One; Public Virtual Int GetNum () {
Return One;
}
}
}
Attribute is characteristic. It can be attached to classes, methods, and variables like labels. We can use it to define information on the design layer or define runtime information. Predefined Attribute To inherit from System.attribute. The following is an example:
[AttributeUSAGE (AttributeTargets.all, inherited = false, allowmultiple = false)]
Public Class DescribeAttribute: Attribute
{
Private string _addname;
Public String AddName
{
get
{
Return_Addname;
}
set
{
_Addname = value;
}
}
Public DescribeAttribute (String a)
{
_Addname = a;
}
}
AttributeUSage represents the situation where Attribute is applicable. The first parameter is the case where the attribute is applicable, and the second parameter represents whether the attribute will be inherited, and the third parameter represents whether the same goal can be repeatedly attached to the Attribute. The following code defines a Class of Attribute that is sticked to above:
"" This is my attribute test. ")]]]]
Public Class Attrtest
{
Public attest ()
{
}
}
Attribute is typically binding to Type, you can get: Getcustomattributes:
DescribeAttribute [] DA = (DescribeAttribute []) TypeOf (atttest) .getcustomattributes (TypeOf (DescribeAttribute), False;
DESCRIBEATTRIBUTE DADA IN DA
Response.write (dada.addname);
Attribute can be bound to the method or variable, below is the code that binds Attribute to the method:
[Describe ("this is a class.")]]]
Public Class Attrtest
{
Public attest ()
{
}
"" This is a method. ")]]]
Public void testmethod ()
{
}
}
Members' methods are obtained by reflection's methodInfo.getcustomattribute (if Attribute on the member variable is used to use the fieldInfo class):
Foreach (MethodInfo Method in Typeof (Attrtest) .getMethods ())
{
DESCRIBEATTRIBUTETRIBUTES (TRUE)
{
Response.write (Attr.Addname);
}
}
Attribute identifier Attribute identifier can declare the placement of Attribute. [Assembly: Help ("this a do-nothing assembly")] The above program tells the compiler HELP property for the entire assembly. The available identifiers include:
askSEMBLY
Module
Type
Method
Property
Event
Field
PARAM
Return