Home  >  Article  >  Backend Development  >  Reflection in C#

Reflection in C#

WBOY
WBOYforward
2023-08-26 13:45:021246browse

C# 中的反射

Reflection objects are used to obtain type information at runtime. Classes that allow access to a running program's metadata are located in the System.Reflection namespace.

The following is an application of Reflections -

  • It allows viewing property information at runtime.

  • It allows checking various types in an assembly and instantiating these types.

  • It allows late binding to methods and properties
  • It allows creating new types at runtime and then using these types to perform some tasks.

  • ul>

    Let’s see an example -

    Example

    using System;
    
    [AttributeUsage(AttributeTargets.All)]
    public class HelpAttribute : System.Attribute {
       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 {
          this.Url = url;
       }
       private string topic;
    }
    
    [HelpAttribute("Information on the class MyClass")]
       class MyClass {
    }
    
    namespace AttributeAppl {
       class Program {
          static void Main(string[] args) {
             System.Reflection.MemberInfo info = typeof(MyClass);
             object[] attributes = info.GetCustomAttributes(true);
    
             for (int i = 0; i < attributes.Length; i++) {
                System.Console.WriteLine(attributes[i]);
             }
             Console.ReadKey();
          }
       }
    }

The above is the detailed content of Reflection in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete