[C # delicious] Use reflection to dynamically create instances and call Methods

Source: Internet
Author: User
Document directory
  • Main purpose:
  • DLL
  • Use reflection to create a class instance in the DLL and call the Method
  • Complete code

In. net, the Assembly stores metadata (metadata) information, so you can obtain the content in the Assembly by analyzing metadata, such as classes, methods, attributes, etc, this greatly facilitates the dynamic creation of instances at runtime.

The msdn explanation is as follows:

Reflection provides encapsulated assembly, module, and type objects (type ). You can use reflection to dynamically create instances of the type, bind the type to an existing object, or obtain the type from the existing object and call its method or access its fields and properties. If attributes are used in the code, you can use reflection to access them.

Main purpose:
  1. Dynamically load DLL to implement plug-in mechanism.
  2. Instantiate the type in the DLL.
  3. Perform post-binding to access the type method created at runtime.

 

Today, I will introduce the following two uses. In fact, the initial purpose is to create a corresponding object based on the values in the configuration file.

 

DLL

First, run the previous Code. This is the classgreenerycn class to be called. It is compiled as dlldemo. dll.

using System;namespace DllDemo{    public class ClassGreenerycn    {        public string Name { get; set; }        public bool IsTest { get; set; }        public void Hello()        {            Console.WriteLine(Name);        }    }}

 

The simple code is that a class has two attributes. The Hello method will output the name to the command line.

 

Use reflection to create a class instance in the DLL and call the Method

Now, create a new command line project. This project is used to dynamically load dlldemo. dll, instantiate an object named greenerycn and istest true, and call the hello method.

The detailed steps are as follows:

1. namespace for referencing reflection:

using System.Reflection;

2. Dynamic DLL Loading

Dynamic DLL loading has three functions:

public static Assembly Load(string assemblyString);
  • This method imports the DLL name, which must be in the GAC global cache. Otherwise, an exception "system. Io. fileloadexception: failed to load the file or assembly" is reported.
public static Assembly LoadFile(string path);
  • This LoadFile is the most convenient. The parameter is the dll path.
public static Assembly LoadFrom(string assemblyFile);
  • This method can also be used. The parameter is also the dll path.

 

3. Obtain the classgreenerycn class type

var type = asm.GetType("DllDemo.ClassGreenerycn");

Note: The complete type name, including the namespace of the signature, is required.

4. Create an instance of this type

var instance = asm.CreateInstance("DllDemo.ClassGreenerycn");

5. Set attributes

type.GetProperty("Name").SetValue(instance, "http://greenerycn.cnblogs.com", null);type.GetProperty("IsTest").SetValue(instance, true, null);

6. Get the hello Method

var method = type.GetMethod("Hello");

7. Call the hello Method

method.Invoke(instance, null);

8. Compile and run

Complete code
using System.Reflection;namespace ReflectionDllDemo{    class Program    {        static void Main(string[] args)        {            var asm = Assembly.LoadFile(@"d:\3_code\DotNet\DllDemo\DllDemo\bin\Debug\DllDemo.dll");            var type = asm.GetType("DllDemo.ClassGreenerycn");            var instance = asm.CreateInstance("DllDemo.ClassGreenerycn");            type.GetProperty("Name").SetValue(instance, "http://greenerycn.cnblogs.com", null);            type.GetProperty("IsTest").SetValue(instance, true, null);            var method = type.GetMethod("Hello");            method.Invoke(instance, null);        }    }}

References:

Reflection (C # programming guide)

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.