zoukankan      html  css  js  c++  java
  • 用Activator.CreateInstance代替new实现类的实例化

    一直想得到这样一个函数,输入一个类的名称为参数,返回一个相应的类的实例.

    这在工厂模式中是非常有用的

    这样,可以使程序有更高的扩展性,例如,,下面的例子

    如果现在有一个类,专门用来计算交通工具的速度,不同的交通工具计算方法是不一样的,但是到底有那些交通工具是未知的或者是可变的,这种情况下,我们可能觉得要在添加交通工具的时候,需要修改用来计算速度的那个类,

    但如果用Activator .CreateInstance创建实例,通过接口技术,则只要向程序集添加一个交通工具类,而不需要修改任何其它代码..实现了高扩展性.,

    示例如下:

    //接口:比如,在上例中,可以是交通工具必需实现的接口
    
    using System;
    
    namespace ActivatorCreateInstance
    {
     /// <summary>
     /// IObjcet 的摘要说明。
     /// </summary>
     public interface IObjcet
     {
      void printName();
     }
    }
    using System;
    
    namespace ActivatorCreateInstance
    {
     /// <summary>
     /// ClassExam 的摘要说明。
     /// </summary>
     public class ClassExam:IObjcet
     {
      private string name="default name";
      public ClassExam()
      {
       
      }
    
      public ClassExam(string name)
      {
       this.name =name;
      }
    
      public void printName()
      {
       Console .WriteLine (this.ToString ()+"'s name is:");
      Console .WriteLine (this.name );
    
      }
      


    namespace
    ActivatorCreateInstance { /// <summary> /// main 的摘要说明。 /// </summary> public class main { public main() { } public static void Main() {//用Activator .CreateInstance创建函数实例,默认的不带参数的构造函数 IObjcet obj=(IObjcet)Activator .CreateInstance(System.Type .GetType ("ActivatorCreateInstance.ClassExam,ActivatorExample" ),null); //System.Type .GetType 命名空间.类名,程序集 obj.printName(); //调用ClassExam类的另一个带参数构造函数 IObjcet obj2=(IObjcet)System.Activator .CreateInstance (System.Type .GetType ("ActivatorCreateInstance.ClassExam,ActivatorExample" ),new string []{"seted new name"}); obj2.printName (); } } }
  • 相关阅读:
    jQueryrocket
    jQueryrocket
    jQueryrocket
    jQueryrocket
    jQueryrocket
    SPListItem.UpdateOverwriteVersion()真的不会创建新版本吗?
    不能访问本地服务器场。没有注册带有FeatureDependencyId 的 Cmdlet
    SharePoint 2013 另一个程序正在使用此文件,进程无法访问。 (异常来自 HRESULT:0x80070020)
    使用PowerShell修改操作系统“环境变量”
    无法解决“Microsoft.SharePoint.Security, Version=15.0.0.0,”与“Microsoft.SharePoint.Security, Version=14.0.0.0”之间的冲突
  • 原文地址:https://www.cnblogs.com/sylone/p/9486959.html
Copyright © 2011-2022 走看看