Simple application example of asp. net reflection

  • 2021-09-12 00:56:15
  • OfStack

In this paper, an example is given to describe the simple application of asp. net reflection. Share it for your reference, as follows:

Reflection provides an object (Type type) that encapsulates assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind a type to an existing object, or get a type from an existing object and call its methods or access its fields and properties. If attributes are used in code, they can be accessed by reflection. This is the simplest understanding of reflection. The following is the simplest example to tell the application of reflection technology!

1. Declare an interface that contains a virtual method. As follows


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
  public interface IReflect
  {
    void Run(string name);
  }
}

2. Implement the interface and implement the methods in the interface. As follows


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
  public class Reflect:IReflect
  {
    public void Run(string name)
    {
      Console.WriteLine(name+" Began to run !");
    }
  }
}

3. Create an instance of a type through reflection technology and call the method of the instance. As follows


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      IReflect rec = (IReflect)Assembly.Load("ConsoleApplication1").CreateInstance("ConsoleApplication1.Reflect");
      rec.Run("aaa");
      Console.ReadLine();
    }
  }
}

So a simple example is completed, and the result displayed is "aaa started to run". The reflected named control is System. Reflection, which must be referenced when used. The object used by the named control is Assembly, which contains many static methods. Among them, Load is very typical. CreateInstance is used to create an instance of an object.

For more readers interested in asp. net, please check the topics on this site: "Summary of asp. net Optimization Skills", "Summary of asp. net String Operation Skills", "Summary of XML Operation Skills", "Summary of asp. net File Operation Skills", "Summary of asp. net ajax Skills" and "Summary of asp. net Cache Operation Skills".

I hope this paper is helpful to everyone's asp. net programming.


Related articles: