Dynamically create objects from strings when the. net instance is running

Source: Internet
Author: User

This article from: http://www.cnblogs.com/godwar/archive/2008/01/17/1042481.html

 

When you see the title, most people will say "create objects at runtime", which is not a pediatrics, just like this:
  
Dim newbutton as button = new button ()
Newbutton. Name = "button1"
  
This is indeed a button created at the runtime. However, if you need to create buttons, check boxes, or single-region as required by the user, it seems that you can do the following:
  
Dim newcontrol as control
Select case userselection
Case "button"
Newcontrol = new button ()
Case "check box"
Newcontrol = new checkbox ()
....
  
End select
  
If you need dozens of controls in windows. Forms, do you need to write dozens of lines in your select statement? Of course I don't want to be a tough user, but there are always a variety of requirements. If there is a way to specify the object creation type at runtime, it is even convenient to create the required object using a string that represents the type name .. Net framwork reflection brings us a solution to the problem. Here, if you only need to create a general object, we can implement it through system. activator, and more complex we can implement it through the get constructor.

Reflection reflection is an important mechanism in. net. Many people have already introduced reflection. Let's review it briefly. Reflection can be obtained at runtime. net members of every type (including class, structure, delegation, interface, and enumeration), including methods, properties, events, and constructors, you can also obtain the names, delimiters, and parameters of each member. With reflection, you can understand each type. If you obtain information about the constructor, you can directly create an object, even if the object type is unknown during compilation.
  
Before creating the control task at runtime, let's take a look at a simple example to create a Windows program named vbappliction, add a new file, and enter a new class:
  
Public class myclasstest
Private myfield as string

Public sub new ()
Myfield = "Hi! "
End sub

Public sub Hello ()
Console. writeline (myfield)
End sub

End Class

Add a new button to the form and enter the following Event code:
  
''Method 1
  
Dim t as type = GetType (myclasstest)
O = system. activator. createinstance (t)
O. Hello ()
  
The first line of the GetType (myclasstest) function has obtained the type object of the class we created (using the typeof function in C ). Next, we use the static method createinstance of the system. activator class to create an object instance and assign the object reference to O. Activator is a tool used to create local or remote objects. Run this program. We can see the result of running the writeline function from the commond window (command window, usually in the lower right of the IDE in the debugging status) and the correctly created object.
  
If the class we use has a complex constructor, you can also use the constructor to create the required object. The Code is as follows:
  
''Method 2
  
Dim t as type = GetType (myclasstest)
Dim C as system. reflection. constructorinfo
Dim types () as type
Redim types (-1)
C = T. getconstructor (reflection. bindingflags. instance _
Or reflection. bindingflags. Public ,_
Nothing, reflection. callingconventions. hasthis, types, nothing)
Dim Params () as object
Redim Params (-1)
O. Hello ()
  
Here we create a system. reflection. constructorinfo object to obtain information about the class constructor. We use the getconstructor method of the type class to search for available constructor methods.

  
You need to explain the types () array, which is the parameter type table used for searching the constructor. The constructor of our class has no parameters, so we need an array that is empty but not null (null in C #). ReDim types (-1) is the statement for creating this array, you can write in C:
  
Types = new Type [0];
  
If the constructor is like this:
  
Public Sub New (ByVal A As Integer, B As String)
  
The corresponding types array should be
  
Dim types (1) As Type
  
Types (0) = GetType (Int32)
  
Types (1) = GetType (String)
  
Reflection. BindingFlags. Instance and Reflection. BindingFlags. Public are a single-bit blocking option that specifies the search method.

The params () array is the parameter content table of the constructor. Because there are no parameters, we use the ReDim-1 syntax.
  
The Invoke method executes the constructor to create an object instance.
  
Now let's go back to the first implementation method and change the code
  
Dim t As Type = GetType (MyClassTest)
  
Change
  
Dim t As Type = Type. GetType ("VBApplication. MyClassTest ")
  
The running result has not changed. That is to say, we have created an object from the string! However, the use of the GetType method is limited here. Now we can achieve our desire: to dynamically create controls. With the above knowledge, we can easily write a subroutine for dynamically creating window controls:
  
Private Function CreateNewControls (ByVal targetControls As Control. ControlCollection, ByVal ctlName As String, ByVal ctlType As Type, ByVal ctlSize As Drawing. Size, ByVal ctlLocation As Drawing. Point) As Control
Dim toCreate As Control
ToCreate = CType (System. Activator. CreateInstance (ctlType), Control)
ToCreate. Name = ctlName
ToCreate. Size = ctlSize
ToCreate. Location = ctlLocation
TargetControls. Add (toCreate)
Return toCreate
End Function
  
The long statement contains all the content in the previous example. If it is written in C #, it can be written
  
ToCreate = (Control) System. Activator. CreateInstance (ctlType );
  
We changed the button event process:
  
Dim c As Control = Me. CreateNewControls1 (Me. Controls, "Control1", GetType (CheckBox), New Size (168, 40), New Point (64,176 ))
  
C. Text = "New Creation"
  
Now, click the button to see a New CheckBox appears in the window with the title New Creation. If the event process is compiled, you can also add event responses to the newly created control.
  
It seems that everything is done? Note that the GetType (CheckBox) still uses the literal expression of the class name, which cannot be used to create objects with strings. Can we change this sentence to Type. GetType ("System. Windows. Forms. CheckBox? Well, try it out. Oh, it's wrong. Why? The Type. GetType () method obtains the Type from the string only by the Type in corlib or the Type inside the project. If the Type is from an external assembly, the Assembly name must be used. Windows. Forms assembly is a public assembly located in the Assembly Cache and can be executed by side in. net Framwork. Therefore, this Assembly has different versions. To determine the version used, we must not only provide the Assembly name, but also provide the Assembly version and strong name. According to this idea. net Framework 1.1, write this sentence as Type. getType ("System. windows. forms. checkBox, System. windows. forms, Version = 1.0.5000.0, Culture = neutral, PublicKeyToken = b77a5c561934e089 "). Now there is no problem. The question is, how do we obtain the version and strong name of the Windows. Forms Assembly used? You can use GetType (CheckBox ). assemblyQualifiedName syntax, once this information is obtained, we can use this information for any other control, because they all come from the same version of Windows. forms assembly. Now you can play a fun game. Put a text box in the window, for example, TextBox1. Change the event process of the button:
  
Try
  
Dim c As Control = Me. createNewControls1 (Me. controls, "Control1", Type. getType ("System. windows. forms. "& TextBox1.Text &", System. windows. forms, Version = 1.0.5000.0, Culture = neutral, PublicKeyToken = b77a5c561934e089 "), New Size (168, 40), New Point (64,176 ))
C. Text = "New Creation"
Catch ex As Exception
MsgBox (ex. Message)
End Try
  
Enter "Button" in TextBox1 and press the Button. A new Button is generated! If the input is CheckBox, a check box is generated. Now, no matter how difficult the user is, the control can be correctly "created on demand. The reflection mechanism is in. net, it is said that class references and virtual constructor functions in Delphi.net are used. net Framwork refers to reflection and System. type implementation, make good use of this tool will give your program a lot of color.

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.