用Activator .CreateInstance

来源:互联网 发布:欧母龙plc编程软件 编辑:程序博客网 时间:2024/05/18 00:37

在工厂模式中是非常有用,可以使程序有更高的扩展性。

Activator .CreateInstance:使用命名的程序集和默认构造函数,创建名称已指定的类型的实例。

例子

创建一个接口,类继承接口,主函数引用接口,如果以后增添新的Person,只需要增加类

namespace InterfaceP{    public interface IObjcet    {        string say();        string Name { get; set; }    }}namespace test.Person{    public class test : IObjcet    {        private string _name;        public string Name        {            get { return this._name; }            set { this._name = value; }        }        public string say()        {            return "test"+_name;        }    }}namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            ObjectHandle handle = Activator.CreateInstance("test.Person", "test.Person.test");//(assembleName,TypeName)            IObjcet p = (IObjcet)handle.Unwrap();            p.Name = "Alice";            Console.WriteLine(p.say());                               }    }}

在另一个程序中调用DLL或者exe除了使用Process,还可以使用System.Reflection.Assembly.LoadFrom


System.Reflection.Assembly assem = System.Reflection.Assembly.LoadFrom("RIOVolOcean.exe");                    Type type = assem.GetType("RIOVolOcean.GetData");                    Object OceanObj = Activator.CreateInstance(type);                    MethodInfo mi = type.GetMethod("Run");                    Object returnValue = mi.Invoke(OceanObj, new object[] { Conn.ConnectionString, request.RequestID.ToString(), listRic });                    

注意:如果要debug必须把pdb文件放到bin目录下面,并且调用方法上 有设置断点


0 0
原创粉丝点击