码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2018-04-23 21:18:13      阅读:462      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!