C#運行時通過字符串實例化類對象(通過類名字符串實例化對象)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
 
namespace CS_Test
{
    public class BaseBullet
    {
        public float x;
        public float y;
        public int color;
        public string name;
 
        public BaseBullet(string name, int color)
        {
            this.name = name;
            this.color = color;
        }
 
        public virtual void say(string str)
        {
            Console.WriteLine(str);
            Console.WriteLine("Name is " + name);
            Console.WriteLine("Color is " + color);
        }
    }
    public class BulletType1 : BaseBullet
    {
        public BulletType1(string name, int color) : base(name, color)
        {
 
        }
 
        public override void say(string str)
        {
            base.say(str);
            Console.WriteLine("shoot from BulletType1");
        }
 
    }
    public class BulletType2 : BaseBullet
    {
        public BulletType2(string name, int color) : base(name, color)
        {
        }
        public override void say(string str)
        {
            base.say(str);
            Console.WriteLine("shoot from BulletType2");
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            int id = 1;
            string className = "CS_Test.BulletType" + id.ToString();
            System.Type t = System.Type.GetType(className);
            BaseBullet b1 = Activator.CreateInstance(t, "John", 1) as BaseBullet;
            b1.say("Hello");
 
            ++id;
            className = "CS_Test.BulletType" + id.ToString();
 
            t = System.Type.GetType(className);
            BaseBullet b2 = Activator.CreateInstance(t, "Sam", 2) as BaseBullet;
            b2.say("Goodbye");
        }
    }
}

 

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

LoaderBase loader = Activator.CreateInstance(Type.GetType(type,true)) as LoaderBase;

 

Activator 類
包含用於在本地創建對象類型的方法。 無法繼承此類。

簡單說 Activator.CreateInstance :使用與指定參數匹配程度最高的構造函數來創建指定類型的實例。

使用Activator.CreateInstance 的實際作用是什么呢?

是因為 想創建一個方法 方法中傳入一個類的名稱 然后就能返回一個這個類的實例 ,這樣的做法讓程序有更高的拓展性,

下面附上 項目中使用的例子

public static OperatorAllLoader OpeatorAllLoader = New("OperatorAllLoader") as OperatorAllLoader;
 private static List<LoaderBase> InfoList = new List<LoaderBase>();
    private static LoaderBase New(string type)
    {    
        // ReSharper disable once AssignNullToNotNullAttribute
        LoaderBase loader = Activator.CreateInstance(Type.GetType(type,true)) as LoaderBase;
        InfoList.Add(loader);
        InfoDict.Add(type, loader);
        return InfoList[InfoList.Count - 1];
    }

還有一個網上的例子

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 ();
  }
 }
}

 

 

 

 

 

 

 

轉: https://blog.csdn.net/weixin_33910759/article/details/93950393

https://blog.csdn.net/ldy597321444/article/details/78362145

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM