SoFunction
Updated on 2025-03-07

Detailed explanation of C# reflection (Reflection)

C# Reflection

Reflection refers to a capability that a program can access, detect and modify its own state or behavior.

An assembly contains modules, and a module contains types, and the type in turn contains members. Reflection provides objects of encapsulation assemblies, modules, and types.

You can use reflection to dynamically create instances of types, bind types to existing objects, or get types from existing objects. Then, a method of type can be called or its fields and properties can be accessed.

Pros and cons

advantage:

1. Reflection improves the flexibility and scalability of the program.
2. Reduce coupling and improve adaptability.
3. It allows programs to create and control objects of any class without hard-code the target class in advance.

shortcoming:

1. Performance issues: Using reflection is basically an explanation operation, which is much slower than direct code when accessing fields and methods. Therefore, the reflection mechanism is mainly used in system frameworks that require high flexibility and expansion, and is not recommended for ordinary programs.
2. Using reflection will blur the internal logic of the program; programmers hope to see the logic of the program in the source code, but reflection bypasses the technology of the source code, which will bring about maintenance problems, and the reflection code is more complicated than the corresponding direct code.

The purpose of reflection

Reflection has the following uses:

  • It allows viewing attribute information at runtime.
  • It allows review of various types in a collection, as well as instantiate these types.
  • It allows delayed binding methods and properties.
  • It allows new types to be created at runtime and then use them to perform some tasks.

View metadata

We have mentioned in the above chapter that you can use reflection to view attribute information.

The MemberInfo object of the class needs to be initialized to discover attributes related to the class. To do this, you can define an object of the target class as follows:

 info = typeof(MyClass);

The following program demonstrates this:

using System;

[AttributeUsage()]
public class HelpAttribute : 
{
  public readonly string Url;

  public string Topic // Topic is a named parameter  {
   get
   {
     return topic;
   }
   set
   {

     topic = value;
   }
  }

  public HelpAttribute(string url) // url is a positional parameter  {
    = url;
  }

  private string topic;
}
[HelpAttribute("Information on the class MyClass")]
class MyClass
{
}

namespace AttributeAppl
{
  class Program
  {
   static void Main(string[] args)
   {
      info = typeof(MyClass);
     object[] attributes = (true);
     for (int i = 0; i < ; i++)
     {
      (attributes[i]);
     }
     ();

   }
  }
}

When the above code is compiled and executed, it displays custom features attached to the class MyClass:

HelpAttribute

Example

In this example, we will use the DeBugInfo feature created in the previous chapter and use reflection to read the metadata in the Rectangle class.

using System;
using ;
namespace BugFixApplication
{
  // A custom property BugFix is ​​assigned to the class and its members  [AttributeUsage( |
   |
   |
   |
  ,
  AllowMultiple = true)]

  public class DeBugInfo : 
  {
   private int bugNo;
   private string developer;
   private string lastReview;
   public string message;

   public DeBugInfo(int bg, string dev, string d)
   {
      = bg;
      = dev;
      = d;
   }

   public int BugNo
   {
     get
     {
      return bugNo;
     }
   }
   public string Developer
   {
     get
     {
      return developer;
     }
   }
   public string LastReview
   {
     get
     {
      return lastReview;
     }
   }
   public string Message
   {
     get
     {
      return message;
     }
     set
     {
      message = value;
     }
   }
  }
  [DeBugInfo(45, "Zara Ali", "12/8/2012",
    Message = "Return type mismatch")]
  [DeBugInfo(49, "Nuha Ali", "10/10/2012",
    Message = "Unused variable")]
  class Rectangle
  {
   // Member variables   protected double length;
   protected double width;
   public Rectangle(double l, double w)
   {
     length = l;
     width = w;
   }
   [DeBugInfo(55, "Zara Ali", "19/10/2012",
      Message = "Return type mismatch")]
   public double GetArea()
   {
     return length * width;
   }
   [DeBugInfo(56, "Zara Ali", "19/10/2012")]
   public void Display()
   {
     ("Length: {0}", length);
     ("Width: {0}", width);
     ("Area: {0}", GetArea());
   }
  }//end class Rectangle 
  
  class ExecuteRectangle
  {
   static void Main(string[] args)
   {
     Rectangle r = new Rectangle(4.5, 7.5);
     ();
     Type type = typeof(Rectangle);
     // traversal of the characteristics of the Rectangle class     foreach (Object attributes in (false))
     {
      DeBugInfo dbi = (DeBugInfo)attributes;
      if (null != dbi)
      {
        ("Bug no: {0}", );
        ("Developer: {0}", );
        ("Last Reviewed: {0}",
                    );
        ("Remarks: {0}", );
      }
     }
     
     // traversal method characteristics     foreach (MethodInfo m in ())
     {
      foreach (Attribute a in (true))
      {
        DeBugInfo dbi = (DeBugInfo)a;
        if (null != dbi)
        {
         ("Bug no: {0}, for Method: {1}",
                        , );
         ("Developer: {0}", );
         ("Last Reviewed: {0}",
                        );
         ("Remarks: {0}", );
        }
      }
     }
     ();
   }
  }
}

When the above code is compiled and executed, it produces the following results:

Length: 4.5
Width: 7.5
Area: 33.75
Bug No: 49
Developer: Nuha Ali
Last Reviewed: 10/10/2012
Remarks: Unused variable
Bug No: 45
Developer: Zara Ali
Last Reviewed: 12/8/2012
Remarks: Return type mismatch
Bug No: 55, for Method: GetArea
Developer: Zara Ali
Last Reviewed: 19/10/2012
Remarks: Return type mismatch
Bug No: 56, for Method: Display
Developer: Zara Ali
Last Reviewed: 19/10/2012
Remarks:

The above is a detailed explanation of C# reflection (Reflection). For more information about C# reflection (Reflection), please follow my other related articles!