C# 通过反射获取实例对象

时间:2020-11-25 05:16:03
namespace XXX5
{
    class A
    {
        public virtual void print()
        {
            Console.WriteLine("this is A");
        }
    }

    class B : A
    {
        public override void print()
        {
            base.print();
        }
    }

    class C : A
    {
        public override void print()
        {
            base.print();
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            //typeof(B)等价于new B().GetType();
            initData(typeof(B));
            initData(new C().GetType());

            Console.ReadKey();
        }

        static void initData(Type t)
        {
            Console.WriteLine(t.ToString());
            A data = Activator.CreateInstance(t) as A;
            data.print();
        }
 }

运行结果:
XXX5.B
this is A
XXX5.C
this is A