📜  C#中的反射是什么?

📅  最后修改于: 2021-05-29 19:31:23             🧑  作者: Mango

反射是描述代码中类型,方法和字段的元数据的过程。命名空间System.Reflection使您能够获取有关已加载程序集及其中的元素(如类,方法和值类型)的数据。一些常用的System.Reflection类是:

Class Description
Assembly describes an assembly which is a reusable, versionable, and self-describing building block of a common language runtime application
AssemblyName Identifies an assembly ith a unique name
ConstructorInfo Describes a class constructor and gives access to the metadata
MethodInfo Describes the class method and gives access to its metadata
ParameterInfo Describes the parameters of a method and gives access to its metadata
EventInfo Describes the event info and gives accessto its metadata
PropertyInfo Discovers the attributes of a property and provides access to property metadata
MemberInfo Obtains information about the attributes of a member and provides access to member metadata

注意:还有许多其他类,上表仅提供有关常用信息的信息。

现在让我们来看一个示例,以描述反射在C#中的工作方式。

示例1:在下面给出的代码中,我们使用typeof方法将类型t作为字符串加载。然后,我们对t进行反射,以查找有关字符串类的任何信息,例如其名称,全名,名称空间和基类型。

// C# program to illustrate
// the use of Reflection
using System;
using System.Reflection;
  
namespace Reflection_Demo {
      
class Program {
      
    // Main Method
    static void Main(string[] args)
    {
        // Initialise t as typeof string
        Type t = typeof(string);
  
        // Use Reflection to find about
        // any sort of data related to t
        Console.WriteLine("Name : {0}", t.Name);
        Console.WriteLine("Full Name : {0}", t.FullName);
        Console.WriteLine("Namespace : {0}", t.Namespace);
        Console.WriteLine("Base Type : {0}", t.BaseType);
    }
}
}

输出:

Name : String
Full Name : System.String
Namespace : System
Base Type : System.Object

示例2:在此代码中,我们使用反射来显示与程序相关的所有元数据,其中包括类,这些类的方法以及与这些参数关联的参数。

// C# program to illustrate
// the use of Reflection
using System;
using System.Reflection;
  
namespace Reflection_Metadata {
      
// Define a class Student
class Student {
      
    // Properties definition
    public int RollNo
    {
        get;
        set;
    }
      
    public string Name
    {
        get;
        set;
    }
  
    // No Argument Constructor
    public Student()
    {
        RollNo = 0;
        Name = string.Empty;
    }
  
    // Parameterised Constructor
    public Student(int rno, string n)
    {
        RollNo = rno;
        Name = n;
    }
  
    // Method to Display Student Data
    public void displayData()
    {
        Console.WriteLine("Roll Number : {0}", RollNo);
        Console.WriteLine("Name : {0}", Name);
    }
}
  
class GFG {
      
    // Main Method
    static void Main(string[] args)
    {
        // Declare Instance of class Assembly
        // Call the GetExecutingAssembly method
        // to load the current assembly
        Assembly executing = Assembly.GetExecutingAssembly();
  
        // Array to store types of the assembly
        Type[] types = executing.GetTypes();
        foreach(var item in types)
        {
            // Display each type
            Console.WriteLine("Class : {0}", item.Name);
  
            // Array to store methods
            MethodInfo[] methods = item.GetMethods();
            foreach(var method in methods)
            {
                // Display each method
                Console.WriteLine("--> Method : {0}", method.Name);
  
                // Array to store parameters
                ParameterInfo[] parameters = method.GetParameters();
                foreach(var arg in parameters)
                {
                    // Display each parameter
                    Console.WriteLine("----> Parameter : {0} Type : {1}",
                                            arg.Name, arg.ParameterType);
                }
            }
        }
    }
}
}

输出:

Class : Student
--> Method : get_RollNo
--> Method : set_RollNo
----> Parameter : value  Type : System.Int32
--> Method : get_Name
--> Method : set_Name
----> Parameter : value  Type : System.String
--> Method : displayData
--> Method : ToString
--> Method : Equals
----> Parameter : obj  Type : System.Object
--> Method : GetHashCode
--> Method : GetType

 Class : Program
--> Method : ToString
--> Method : Equals
----> Parameter : obj  Type : System.Object
--> Method : GetHashCode
--> Method : GetType