C#运行时通过字符串实例化类对象

2021-07-15 18:18

阅读:444

标签:bye   activator   from   c#   ati   main   rtu   creat   static   

备忘,记个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");
        }
    }
}

  

C#运行时通过字符串实例化类对象

标签:bye   activator   from   c#   ati   main   rtu   creat   static   

原文地址:https://www.cnblogs.com/kileyi/p/8921731.html


评论


亲,登录后才可以留言!