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

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

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011484013/article/details/51735822
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭