C # Using Reflection to dynamically create objects [excerpt]

Source: Internet
Author: User

From: http://hi.baidu.com/yangyuhang/blog/item/f12ea90e13f214e336d12250.html

In VS. Net, there are many methods to dynamically call object constructors. First, use the CreateInstance () method of the Activator class. This method is also used in Remoting. It actually creates an object type locally or remotely, or gets a reference to an existing remote object. Its method signature is: public static object CreateInstance (Type); (there are other overload methods). Note that its return value is object. The return value of MSDN is described as follows:

The second is to use the CreateInstance () method of the Assembly class (). The method name is the same as the previous one, but it is not a static method. Assembly is in the System. Reflection namespace. Method Signature: public object CreateInstance (Type); (there are also other overload methods). The returned value is still object, and the return value is described by MSDN as follows:

Of course, there are other methods. For example, after obtaining method information through MethodInfo, determine whether to construct a function based on the IsConstructor attribute, obtain parameters based on the GetParamters () method, and finally call the method through the Invoke () method, and so on ....... You can refer to MSDN.

Here, I want to simplify the problem and only call its default constructor. Use the CreateInstance () method to obtain the object and then convert it to the actual custom object type. It turns out that this conversion is abnormal. I still don't know the root cause. The preliminary guess is that for dynamically loaded assemblies and manually added assemblies, the Framework regards the two as different assemblies, even if we use the same DLL.

I also noticed that Actovator. CreateInstance () returns a reference to the newly created object. Is it just a reference? However, the Assembly. CreateInstance () method returns an object instance according to the description of MSDN, but the same exception is still thrown. Therefore, I cannot explain the specific cause of the problem.

Indeed VS. Net is profound and profound, and many internal operating mechanisms are unknown. Well, we should know it, but we don't know why. At least I am now! As long as it is used, you can leave and seek the second.

Using Reflection to dynamically create objects is actually using Assembly to dynamically load DLL. The so-called "object" can be divided into two types. The solution varies with different types.

1. class objects provided by. Net, such as Form objects and Control objects.

This is also frequently used in program development. Generally, we develop applications to define the interface. How many windows are there, how many controls are there, and put them in the project in advance. However, when designing interactions, you also need to consider user requests. You may want some forms to determine the loading time. That is to say, it is necessary to provide the runtime loading function. In this case, you need to dynamically create an object through reflection. (The loaded form object dll is usually placed in the configuration file. In. Net, there is a special configuration file, which is in xml format. I want to write a special article about the configuration file. In this article, my example is fixed assembly loading .) 1. Create a form object to be dynamically loaded

First, create a form object FirstForm, which has only one control Lable to display the name of the form. Then we compile it into the dll file FirstForm. dll and put it in e:/AutoForm. (To generate a Dll file instead of exe, right-click the FirstForms project in Solution Explorer and select Properties ). Select Class Library in the Output Type combo box ).)

The Assembly name of this object is FirstForm. dll and the type is FirstForm. Form1.

2. Create an application and dynamically load the object

Start a new Windows form project. Name it AutoLoadForm. In the blank form Form1 contained in the new projectIsMdiContainerProperty changedTrue. In this way, the form becomes an MDI parent form. Change the size of the form so that the length and width of the form are approximately twice the default size.

Drag a panel control to the form and set itsDockProperty to connect it to the top of the form. Change the Panel size so that it is about 50px in height.

Drag a combo box to the Panel. Name it cboForms, and thenDropDownStyleSetDropDownList.

Finally, drag a button to the Panel. Name it btnLoadForm, and thenTextSet propertyLoad Form.

In this case, Form1 should be 1.

Then add the namespace for the Program: using System. Reflecton;

Click the btnLoadForm control and write the following code:

Private void btnLoadForm_Click (object sender, System. EventArgs e)
{
Assembly assembly = Assembly. LoadFrom (@ "e: \ AutoFormFirstForm. dll ");
Type type = assembly. GetType ("FirstForm. Form1 ");
Object obj = Activator. CreateInstance (type );
Form formToShow = (Form) obj;
FormToShow. MdiParent = this;
FormToShow. Show ();
}

Code Description: 1) First, load the dll file through Assembly. LoadFrom (); 2) then use GetType () to obtain the type of the Form class object to be created. Note: In the GetType () method, the parameter is of the type name, which is of the string type, and the parameter must be of the type FullName, that is, the namespace name. class Name; 3) then use Activator. the CreateInstance () method creates an object of this type and returns an object. 4) Forcibly convert the object to Form type. 5) The call is complete.

Run the program and click the button. The result is as follows:

Conclusion: we can see that for the Class Object provided by. Net itself, we can directly forcibly convert it. No problems.

Ii. Custom object

As mentioned earlier, forced conversion of custom objects throws an exception. Therefore, we need to make some changes.

We said that the Dynamically Loaded Dll and manually added dll references will not be considered as the same Assembly. So what should we do? Think about it. By the way, you should use interfaces. However, the method for using interfaces here is a little special. Follow the steps to explain. 1. Create an interface that includes methods and attributes for loading object classes:

Create a new "class library" project named AutoObjectInterface:

Using System;

Namespace AutoObjectInterface
{
Public interface IAutoObject
{
Void Print (string s );
}
}

This interface is very simple. It only provides a Print () method.

Compile it into a Dll file named AutoObjectInterface.

2. Create a custom Class Object:

Create a new "class library" project named AutoObject and add the aforementioned interface Dll reference:

Using System;

Namespace AutoObject
{
Public class TestObject: AutoObjectInterface. IAutoObject
{
Public TestObject ()
{

}

Public void Print (string s)
{
Console. WriteLine (s );
}
}
}

This class implements the interface created in step 1. Note that the interface implemented here is not directly written in this class, but an independent Dll. In this class, it is the dll with this interface added, and then implement it. This is a special aspect of the interface used previously.

 

Obj = (AutoObjectInterface. IAutoObject) obj;

Using System;
Using System. Reflection;


Namespace studyReflection
{
Class Class1
{

// Main entry point of the application.
[STAThread]
Static void Main (string [] args)
{
Assembly assembly = Assembly. LoadFrom (@ "e: NewObjectAutoObject. dll ");
Type type = assembly. GetType ("AutoObject. TestObject ");

Object obj = Activator. CreateInstance (type );
AutoObjectInterface. IAutoObject iObj = (AutoObjectInterface. IAutoObject) obj;

IObj. Print ("wayfarer ");

Console. ReadLine ();
}
}
}

Note: This code is similar to the object provided by. Net itself. The key difference is forced conversion. Because it is a custom object, we do not know why the conversion is performed, so we need to add an interface reference. Convert to the interface type during conversion:

Related Article

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.