C# Reflection Basics

start

 1. The namespace used

    System.Reflection
    System.Type
    System.Reflection.Assembly

Two, the main category

    System.Type Class -- This class provides access to information for any given data type.
    System.Reflection.Assembly class - This can be used to access information about a given assembly, or to load this assembly into a program.

illustrate

 1. System.Type class

 The System.Type class plays a central role in reflection. It is an abstract base class. Type has derived classes corresponding to each data type. We use the methods, fields, and properties of objects of this derived class to find all information about the type.

Represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types.

Parse type information from Type:

 A. A common way to judge references of a given type:

1. Using the C# typeof operator

 Type t = typeof(string);

2. Use the object GetType() method

  string s = "i3yuan";
  Type t2 = s.GetType();

3. Call the static method GetType() of the static Type class

  Type t3 = Type.GetType("System.String");

After obtaining the type Type in the above three ways, you can use t to detect the structure in the string

  foreach (MemberInfo mi in t.GetMembers())
  {
       Console.WriteLine("{0}/t{1}", mi.MemberType, mi.Name);
  }

B. Type class attributes:

  1. Namespace and type name

        Name The data type name
        FullName The fully qualified name of the data type (including the namespace name)
        Namespace The namespace name that defines the data type

  2. Classes and delegates

        Type.IsClass Determines whether a type is a class or a delegate. Those who meet the conditions will have ordinary classes (including generics), abstract classes (abstract class), and delegates (delegate)

  3. Is it generic  

        The Type.IsGenericType attribute can determine whether a class or delegate is a generic type.

        The Type.IsGenericTypeDefinition attribute can determine whether the Type is a generic type of an unbound parameter type.

        The Type.IsConstructedGenericType attribute determines whether this Type can create a generic instance.

  4. Access modifiers

        Type.IsPublic Determines whether the type is public

        Type.IsNotPublic

  5. Sealed class, static type, abstract class

        Type.IsSealed Determines whether the type is a sealed class, and sealed classes cannot be inherited

        IsAbstract indicates whether the type is an abstract type

  6. Value types

        Type.IsValueType judges whether a Type is a value type, and simple value types, structures, and enumerations all meet the requirements.

        Type.IsEnum determines whether the type is an enumeration

        Type.IsPrimitive Determines whether Type is a basic type

  7. Interface

        Type.IsInterface determines whether the type is an interface

  8. Array

        IsArray Determines whether the type is an array, and GetArrayRank() obtains the dimension of the array.

Parse type member structure from Type class

A class consists of one or more of the following members:

member type illustrate
PropertyInfo Type attribute information
FieldInfo Type field information
ConstructorInfo type constructor information
MethodInfo type of method
ParameterInfo Parameters of constructor or method
EventInfo type of event

C. Methods of the Type class

public class MySqlHelper
    {
        public MySqlHelper()
        {
            Console.WriteLine("{0}被构造", this.GetType().Name);
        }


        public void Query()
        {
            Console.WriteLine("{0}.Query", this.GetType().Name);
        }
    }

        GetConstructor(), GetConstructors(): return ConstructorInfo type, used to obtain information about the constructor of this class

MySqlHelper dBHelper = new MySqlHelper();
Type type = dBHelper.GetType();
ConstructorInfo[] constructorInfos= type.GetConstructors();
foreach (var item in constructorInfos)
{
    ParameterInfo[] parameterInfos = item.GetParameters();
    foreach (var info in parameterInfos)
    {
           Console.WriteLine("查看:" + info.ParameterType.ToString() + "  " + info.Name);
    }
}

        GetEvent(), GetEvents(): Return the EventInfo type, used to obtain information about events of this class

        GetField(), GetFields(): Return the FieldInfo type, used to obtain information about the fields (member variables) of this class

        MySqlHelper nc = new MySqlHelper();
        Type t = nc.GetType();
        FieldInfo[] fis = t.GetFields();
        foreach (FieldInfo fi in fis)
        {
            Console.WriteLine(fi.Name);
        } 

        GetInterface(), GetInterfaces(): Returns the InterfaceInfo type, used to obtain information about the interface implemented by the class

        GetMember(), GetMembers(): return the MemberInfo type, used to obtain information about all members of the class

            string n = "i3yuan";
            Type t = n.GetType();
            foreach (MemberInfo mi in t.GetMembers())
            {
                Console.WriteLine("{0}/t{1}",mi.MemberType,mi.Name);
            }

        GetMethod(), GetMethods(): Return the MethodInfo type, used to obtain information about the methods of this class

        MySqlHelper dBHelper= new MySqlHelper();
        Type t = dBHelper.GetType();
        MethodInfo[] mis = t.GetMethods();
        foreach (MethodInfo mi in mis)
        {
            Console.WriteLine(mi.ReturnType+" "+mi.Name);
        }

        GetProperty(), GetProperties(): Return the PropertyInfo type, used to obtain information about the properties of this class

        MySqlHelper dBHelper= new MySqlHelper();
        Type t = dBHelper.GetType();
        PropertyInfo[] pis = t.GetProperties();
        foreach(PropertyInfo pi in pis)
        {
            Console.WriteLine(pi.Name);
        }

  These members can be invoked by calling the InvokeMember() method of Type, or by calling the Invoke() method of MethodInfo, PropertyInfo, and other classes. 

  Use reflection to generate objects and call properties, methods and fields for operations 

        //获取类型信息
        MySqlHelper dbHelper=new MySqlHelper();
        Type type=dbHelper.GetType
        //创建对象实例化
        object DbHelper = Activator.CreateInstance(type);
        //类型转换
        IDBHelper iDBHelper = (IDBHelper)DbHelper;
        //方法调用
        iDBHelper.Query();  

Two, System.Reflection.Assembly class

   The Assembly class can obtain assembly information, dynamically load the assembly, find type information in the assembly, and create an instance of the type. Using the Assembly class can reduce the coupling between assemblies, which is conducive to the rationalization of software structure

 1. System.Reflection 

Used to access information about a given assembly, or to load this assembly into a program. Can read and use metadata

Method call process:

1. Load DLL; 2. Obtain type information; 3. Create object type 4. Type conversion 5. Method call

Assembly assembly = Assembly.Load("Yuan.DB.MySql");//dll名称无后缀  从当前目录加载  1 加载dll
/完整路径的加载  可以是别的目录   加载不会错,但是如果没有依赖项,使用的时候会错
Type type = assembly.GetType("Yuan.DB.MySql.MySqlHelper");//2 获取类型信息
object oDBHelper = Activator.CreateInstance(type);//3 创建对象
//oDBHelper.Query();//oDBHelper是objec不能调用,但实际上方法是有的   编译器不认可  
IDBHelper iDBHelper = (IDBHelper)oDBHelper;//4 类型转换
iDBHelper.Query();//5 方法调用

Method 2: Reflection through the name of the assembly

Assembly assembly = Assembly.Load("Yuan.DB.MySql");//dll名称无后缀  从当前目录加载  1 加载dll
               
Type type = assembly.GetType("Yuan.DB.MySql.MySqlHelper");//2 获取类型信息

object oDBHelper = Activator.CreateInstance(type);//3 创建对象
MethodInfo mi=oDBHelper.GetMethod("Query"); //获取方法
mi.Invoke(oDBHelper,null);//5 调用

Guess you like

Origin blog.csdn.net/ttod/article/details/130279648