Home  >  Article  >  Backend Development  >  C# uses reflection to create an instance object of a class based on the class name.

C# uses reflection to create an instance object of a class based on the class name.

黄舟
黄舟Original
2017-03-16 10:57:502732browse

This article mainly introduces the detailed explanationC#Using reflection to create an instance of a class based on the class nameObject, "reflection" actually uses the metadata information of the assembly, if you are interested Friends, you can refer to it.

"Reflection" actually uses the metadata information of the assembly. Reflection can have many methods. When writing a program, please import System.Reflection namespace first.

1. Suppose you want to reflect a class in DLL, and there is no reference to it (that is, an unknown type):


Assembly assembly = Assembly.LoadFile("程序集路径,不能是相对路径"); // 加载程序集(EXE 或 DLL) 
dynamic obj = assembly.CreateInstance("类的完全限定名(即包括命名空间)"); // 创建类的实例

2. To reflect the class in the current project (that is, the current project has already referenced it) can be:


Assembly assembly = Assembly.GetExecutingAssembly(); // 获取当前程序集 
dynamic obj = assembly.CreateInstance("类的完全限定名(即包括命名空间)"); 
// 创建类的实例,返回为 object 类型,需要强制类型转换

3. It can also be:


Type type = Type.GetType("类的完全限定名"); 
dynamic obj = type.Assembly.CreateInstance(type);

4. If it is a different assembly, then To load the call, the code is as follows:

System.Reflection.Assembly.Load("Assembly name (excluding file suffix name)").CreateInstance("Namespace.Class name" , false);

For example:

The code is as follows:

dynamic o = System.Reflection.Assembly.Load("MyDll").CreateInstance("MyNameSpace.A", false);

Note:Due to the need to use dynamic, the target needs to be changed to 4.0. If the error "Cannot find one or more types required to compile dynamic expression. Are there missing references?" error occurs during compilation, yes Because there is a missing reference, reference Miscorsoft.CSharpClass Library in the project, and it will compile successfully after adding it.

============================================ ==============

Supplement:

1) When creating an instance of a class by reflection, you must ensure that you use the Fully qualified name (namespace + class name). If the Type.GetType method returns null, it means that the search for relevant information in metadata fails (reflection fails). Please make sure to use the fully qualified name of the class when reflecting.

2) The reflection function is very powerful, and there is nothing that cannot be achieved. If you want to implement "cross-assembly", please use the first method to create an instance of the class and reflect the fields, properties, methods, events... and then call it dynamically. .


  /// <summary>
  /// 反射帮助类
  /// </summary>
  public static class ReflectionHelper
  {
    /// <summary>
    /// 创建对象实例
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fullName">命名空间.类型名</param>
    /// <param name="assemblyName">程序集</param>
    /// <returns></returns>
    public static T CreateInstance<T>(string fullName, string assemblyName)
    {
      string path = fullName + "," + assemblyName;//命名空间.类型名,程序集
      Type o = Type.GetType(path);//加载类型
      object obj = Activator.CreateInstance(o, true);//根据类型创建实例
      return (T)obj;//类型转换并返回
    }

    /// <summary>
    /// 创建对象实例
    /// </summary>
    /// <typeparam name="T">要创建对象的类型</typeparam>
    /// <param name="assemblyName">类型所在程序集名称</param>
    /// <param name="nameSpace">类型所在命名空间</param>
    /// <param name="className">类型名</param>
    /// <returns></returns>
    public static T CreateInstance<T>(string assemblyName, string nameSpace, string className)
    {
      try
      {
        string fullName = nameSpace + "." + className;//命名空间.类型名
        //此为第一种写法
        object ect = Assembly.Load(assemblyName).CreateInstance(fullName);//加载程序集,创建程序集里面的 命名空间.类型名 实例
        return (T)ect;//类型转换并返回
        //下面是第二种写法
        //string path = fullName + "," + assemblyName;//命名空间.类型名,程序集
        //Type o = Type.GetType(path);//加载类型
        //object obj = Activator.CreateInstance(o, true);//根据类型创建实例
        //return (T)obj;//类型转换并返回
      }
      catch
      {
        //发生异常,返回类型的默认值
        return default(T);
      }
    }
  }

The above is the detailed content of C# uses reflection to create an instance object of a class based on the class name.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn