Home  >  Article  >  Backend Development  >  asp.net reflection simple application example

asp.net reflection simple application example

高洛峰
高洛峰Original
2017-02-20 17:08:561262browse

The examples in this article describe the simple application of asp.net reflection. Share it with everyone for your reference, as follows:

Reflection provides objects (Type types) that encapsulate assemblies, modules and types. You can use reflection to dynamically create instances of a type, bind the type to an existing object, or get the type from an existing object and call its methods or access its fields and properties. If properties are used in your code, you can use reflection to access them. ----This is the simplest understanding of reflection. The following is the simplest example to describe the application of reflection technology!

1. Declare the interface, which 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+"开始跑了!");
    }
  }
}

3. Use reflection technology to create an instance of the type and call the instance method. 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();
    }
  }
}

Such a simple example is completed, and the displayed result is "aaa started running". The named control of reflection is System.Reflection. You must refer to this named control when using it. The long-used object of this 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 articles related to asp.net reflection simple application examples, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn