zoukankan      html  css  js  c++  java
  • C#反射通过类名的字符串获取生成对应的实例

    在.net core 1.1环境下

    今天项目中遇到这个问题了,稍微查了一下并没有现成的样例。自己实现了。

    1        static void Main(string[] args)
    2         {
    3             TestGetAssembly();
    4         }
            static void TestGetAssembly()
            {
                AssemblyName name=new AssemblyName("Reflect");//我的程序集的名称为"Reflect"
                var result = Assembly.Load(name);       
                Console.WriteLine(result.FullName);
                TestGetIntance(result);
            }
    
            static void TestGetIntance(Assembly assembly)
            {
                Users user= (Users)assembly.CreateInstance("Reflect.Users");//这里要写的格式为“命名空间.类名称”,切记!
                user.ID = 1;
                Console.WriteLine(user.ID);
            }

    更新:

    发现了一种更简单的方法(构造函数无参数的情况)

            public T GetInstance<T>(string instanceName)
            {
                
                return (T)Assembly.Load(Assembly.GetAssembly(typeof(T)).GetName().Name).CreateInstance(typeof(T).Namespace+"."+instanceName);
    
            }

     构造函数有参的情况(参数param 表示要传递给生成实例构造函数的参数)

            public static T GetInstance<T>(string instanceName,params object[] param)
            {           
                return (T)Assembly.Load(Assembly.GetAssembly(typeof(T)).GetName().Name).CreateInstance(typeof(T).Namespace+"."+instanceName,true,BindingFlags.CreateInstance,null, param,Thread.CurrentThread.CurrentCulture,null);
            }
        

    查看程序集的名称方法为右键项目,点击属性就可以查看到程序集名称,和命名空间了。

  • 相关阅读:
    设计模式-结构型模式总结
    设计模式-享元模式
    设计模式-组合模式
    设计模式-桥接模式
    设计模式-装饰器模式
    设计模式-外观模式
    设计模式-代理模式
    设计模式-适配器模式
    VMware该虚拟机似乎正在使用中
    BurpSuite-Burp Proxy
  • 原文地址:https://www.cnblogs.com/qulianqing/p/6842829.html
Copyright © 2011-2022 走看看