Examples of C# reflection

catalogue

Experimental requirements

background

Step 1. Get a dll file

Step 2. Build a txt file

Step 3. Use reflection to view member information

Step 4. User selects calling method

Step5. Random call

  Operation results

  code

Experimental requirements

Build a components.txt file, and each line represents the name of a class (such as Shape class) (these classes can be from the system library or constructed by themselves); The program scans the file line by line to build the object of the corresponding class.

requirement:

1. And put these objects into the array;

2. List the fields and methods of each class;

3. Let the user select so that the user can call the required method (operation)

4. The system randomly selects objects (such as shapes) and randomly performs their operations. So as to see the system evolution. If possible, display the interface

background

Function of reflection:

  1. Properties that require access to program metadata
  2. Checking and instantiating types in assemblies
  3. Build new types at run time
  4. Perform late binding to access methods of types created at run time

Step 1. Get a dll file

  1. Create a new C# console project and add a. CS file. A Graphics.cs file is used here. The code content is as follows.
  2. Compile this file with the command line and get its dll file.
  3. path C:\Windows\Microsoft.NET \Framework\v2.0.50727 / / normally, the folder location of csc.exe

cd C:\ShapeClass\ShapeClass     // Project location

csc/target:library Graphic.cs  

You can find the. dll file in the project path

What is a dll file?   

. DLL, Dynamic Link Library, DLL in English, is the abbreviation of Dynamic Link Library. A DLL is a library that contains code and data that can be used by multiple programs at the same time.  

Why use dll files?

When a program uses a DLL, it has the following advantages: less resources are used. When multiple programs use the same function library, the DLL can reduce the duplication of code loaded on disk and physical memory.

Popularizing modular architecture DLL helps to promote the development of modular programs. This can help you develop large programs that require multiple language versions or programs that require a modular architecture.

  What is csc.exe?

  C #'s compiler   

Command: csc File.cs                              // Compile the file to generate an exe file

Command: csc/target:library File.cs         // Compile the file to generate a dll file

 

4. Create a new Windows Forms application (. Net Framework) and move the dll file to this project

D:\C # course study \ Draw\Draw\bin\Debug

 

 

Step 2. Build a txt file

1. Build a Shape.txt file, each line represents a class. The program scans the file line by line to build the object of the corresponding class, so write in it:

Rectangle

Triangle

Sphere

Ellipse

2. Move this file to the same location where the same dll is moved D:\C# course study \ Draw\Draw\bin\Debug

Step 3. Use reflection to view member information

1. Add namespace

using System.Reflection;

using System.Collections;

using System.IO;

2. Read txt file

string textpath = "Shape.txt";

FileStream Fp = File.OpenRead(textpath);

StreamReader STREAMR = new StreamReader(Fp, Encoding.Default);

Fp.Seek(0, SeekOrigin.Begin);

3. Load assembly

Assembly assembly = Assembly.LoadFrom("Graphics.dll");

//Loading an assembly: cs file generates a. dll file, which is an assembly

Console.WriteLine("name of assembley:" + assembly.GetName());

//Write out the name of the assembly

4. public ArrayList classList = new ArrayList(); // Build a dynamic array to store the built objects

5.

 

                1. string classname            // Used to store the contents of each line of txt

                2. object[]ars={3,4}               // Parameters related to the contents of dll are not important

                3. / / build entity

 

 

Function source code

public object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object [] args, CultureInfo culture, object [] activationAttributes);

                4.

                 Assembly class: it allows you to load / understand / manipulate an assembly

                 Type class: the main way to access the original data. Type class includes class type / interface type / array type / value type/

                 Enumeration types / type parameters / generic type definitions, and open or closed constructed generic types

                GetType:        Person pe=new Person();

                                             Type t=pe.GetType();      

                        // Returns a Type object of the specified Type. t is a Type object of Person Type

                MethodInfo class: it can find method information

                FieldInfo class: it can find field information


6. Display the obtained information on the form through the label control.

 

Step 4. User selects calling method


  1. Three groupboxes are arranged on the form, with built-in Radio Button s and external buttons for generating results.

  2. Function call: meth[i].Invoke(object,null)

 

 

Step5. Random call

  1. Generation of random numbers

                Random myrandom = new Random();

               int classNum = myrandom.Next(0, 3);

Random class

The default nonparametric constructor of Random class can carry out a series of algorithms to obtain pseudo-Random numbers within the required range according to the current system clock

Random rd = new Random();

int i = rd.Next();

  1. The operation after obtaining the random number is the same as "independent selection"

  Operation results

 

  code

Graphics.cs

using System;

namespace ShapeClass
{
    public class Rectangle
    {
        protected double x, y;        
        public Rectangle(double x1,double y1)
        {
            x = x1;
            y = y1;
        }
        public  double areaR()
        {
            return x * y;
        }
        public double lengthR()
        {
            return 2 * (x + y);
        }
    }
   public class Triangle
    {
        protected double x, h;
        public Triangle(double x1, double y1)
        {
            x = x1;
            h = y1;
        }
        public double areaT()
        {
            return x * h/2;
        }
        public double lengthT()
        {
            return Math.Sqrt(x * x / 4 + h * h) * 2 + x;
        }
    }
    public class Sphere
    {
        protected double r;
        public Sphere(double r1)
        {
            r = r1;
        }
        public double areS()
        {
            return 3.14 * r * r;
        }
        public double lengthS()
        {
            return 6.28 * r;
        }
    }
    public class Ellipse
    {
        protected double a, b;
        public Ellipse(double a1,double b1)
        {
            a = a1;
            b = b1;
        }
        public double areaE()
        {
            return 3.14 * a * b;
        }
        public double lengthE()
        {
            return 6.28* b + 4 * (a - b);
        }
    }
}

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Collections;

namespace Draw
{
    public partial class Form1 : Form
    {
        public ArrayList classList = new ArrayList();
        public Form1()
        {
            InitializeComponent();

            Assembly assembly = Assembly.LoadFrom("Graphics.dll");//Loading an assembly: cs file generates a. dll file, which is an assembly
            Console.WriteLine("name of assembley:" + assembly.GetName());//Write out the name of the assembly            

            //Build the object of the corresponding class
            string textpath = "Shape.txt";
            FileStream Fp = File.OpenRead(textpath);
            StreamReader STREAMR = new StreamReader(Fp, Encoding.Default);
            Fp.Seek(0, SeekOrigin.Begin);

            string classname;
            while (STREAMR.Peek() > -1)
            {
                classname = STREAMR.ReadLine();
                object[] ars = { 3, 4 };
                object shapex = assembly.CreateInstance("Graphics." + classname, true, BindingFlags.Default, null, ars, null, null);
                classList.Add(shapex);
                Type reshape = shapex.GetType();
                
                if (shapex != null)                   
                    label2.Text = label2.Text+"\n\n\n\n\n\n"+Convert.ToString(classList.Count)+"Class name:"+reshape.Name;
                //List the fields and methods of each class;
                MethodInfo[] methodnum = reshape.GetMethods();
                label4.Text = label4.Text+ "\n\n\n\n\n" + reshape.FullName+"Number of methods:" + Convert.ToString(methodnum.Length)+"\n";
                for (int j = 0; j < methodnum.Length; j++)
                {                    
                    label5.Text = label5.Text + Convert.ToString(j + 1) + "." + methodnum[j].Name+"\n";                    
                }
                label5.Text = label5.Text + "\n";
                //List fields
                FieldInfo[] tagnum = reshape.GetFields();              
                label6.Text =label6.Text+ "\n\n\n\n\n" + reshape.FullName + "Number of fields:"+ Convert.ToString(tagnum.Length ) + "\n";
                for (int k = 0; k < tagnum.Length; k++)
                {
                    Console.WriteLine("({0}){1}", k + 1, tagnum[k].Name);
                    label7.Text = label7.Text + Convert.ToString(k + 1) + "." + tagnum[k].Name + "\n";
                }
            }
        }


        private void button_Click(object sender, EventArgs e)
        {
            if(radioButton2.Checked )
            {
                //random number             
                Random myrandom = new Random();
                int classNum = myrandom.Next(0, 3);

                object myobject = classList[classNum];//Randomly select a class
                int numfangfa;
                while (true)
                {
                    numfangfa = myrandom.Next(1, 6);
                    if (numfangfa != 3&&numfangfa!=6)
                        break;
                }
                Type leixing = classList[classNum].GetType();
                MethodInfo[] methoddn = leixing.GetMethods();
         
                string s = Convert.ToString(methoddn[numfangfa - 1].Invoke(myobject, null));
                label1.Text =leixing .Name+"+"+ methoddn[numfangfa - 1].Name+":"+ methoddn[numfangfa - 1].Invoke(myobject, null);
            }
            else if(radioButton1.Checked )        //That is, the user selects the "autonomous call" button
            {
                if(radioButton3.Checked )         //The first shape is selected
                {
                        object myshape = classList[0];
                        Type shapelei = classList[0].GetType();
                        MethodInfo[] meth = shapelei.GetMethods();
                    if(radioButton10.Checked )      //Different method buttons selected
                    {                        
                        string s= Convert.ToString(meth[0].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[0].Name + ":" + meth[0].Invoke(myshape, null);               
                    }
                    else if (radioButton9.Checked)
                    {
                        string s = Convert.ToString(meth[1].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[1].Name + ":" + meth[1].Invoke(myshape, null);
                    }
                    else if (radioButton8.Checked)
                    {
                        string s = Convert.ToString(meth[3].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[3].Name + ":" + meth[3].Invoke(myshape, null);
                    }
                    else if (radioButton7.Checked)
                    {
                        string s = Convert.ToString(meth[4].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[4].Name + ":" + meth[4].Invoke(myshape, null);
                    }
                }
                if (radioButton4.Checked)
                {
                    object myshape = classList[1];
                    Type shapelei = classList[1].GetType();
                    MethodInfo[] meth = shapelei.GetMethods();
                    if (radioButton10.Checked)
                    {
                        string s = Convert.ToString(meth[0].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[0].Name + ":" + meth[0].Invoke(myshape, null);
                    }
                    else if (radioButton9.Checked)
                    {
                        string s = Convert.ToString(meth[1].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[1].Name + ":" + meth[1].Invoke(myshape, null);
                    }
                    else if (radioButton8.Checked)
                    {
                        string s = Convert.ToString(meth[3].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[3].Name + ":" + meth[3].Invoke(myshape, null);
                    }
                    else if (radioButton7.Checked)
                    {
                        string s = Convert.ToString(meth[4].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[4].Name + ":" + meth[4].Invoke(myshape, null);
                    }
                }
                if (radioButton5.Checked)
                {
                    object myshape = classList[2];
                    Type shapelei = classList[2].GetType();
                    MethodInfo[] meth = shapelei.GetMethods();
                    if (radioButton10.Checked)
                    {
                        string s = Convert.ToString(meth[0].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[0].Name + ":" + meth[0].Invoke(myshape, null);
                    }
                    else if (radioButton9.Checked)
                    {
                        string s = Convert.ToString(meth[1].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[1].Name + ":" + meth[1].Invoke(myshape, null);
                    }
                    else if (radioButton8.Checked)
                    {
                        string s = Convert.ToString(meth[3].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[3].Name + ":" + meth[3].Invoke(myshape, null);
                    }
                    else if (radioButton7.Checked)
                    {
                        string s = Convert.ToString(meth[4].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[4].Name + ":" + meth[4].Invoke(myshape, null);
                    }
                }
                if (radioButton6.Checked)
                {
                    object myshape = classList[3];
                    Type shapelei = classList[3].GetType();
                    MethodInfo[] meth = shapelei.GetMethods();
                    if (radioButton10.Checked)
                    {
                        string s = Convert.ToString(meth[0].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[0].Name + ":" + meth[0].Invoke(myshape, null);
                    }
                    else if (radioButton9.Checked)
                    {
                        string s = Convert.ToString(meth[1].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[1].Name + ":" + meth[1].Invoke(myshape, null);
                    }
                    else if (radioButton8.Checked)
                    {
                        string s = Convert.ToString(meth[3].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[3].Name + ":" + meth[3].Invoke(myshape, null);
                    }
                    else if (radioButton7.Checked)
                    {
                        string s = Convert.ToString(meth[4].Invoke(myshape, null));
                        label1.Text = shapelei.Name + "+" + meth[4].Name + ":" + meth[4].Invoke(myshape, null);
                    }
                }

            }
        }
   
    }
}

Tags: C# reflection

Posted on Mon, 01 Nov 2021 07:29:19 -0400 by explorer