欢迎光临
我们一直在努力

.NET反射的简单示例-.NET教程,.NET Framework

建站超值云服务器,限时71元/月

 

(1)namespace classlibrarysport

{

    public abstract class sport

    {

        protected string name;

        public abstract string getname();

        public abstract string getduration();

    }

}

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

(2)namespace classlibrarysomesports//该项目添加了对(1)的引用

{

    public class football : classlibrarysport.sport

    {

        public football()

        {

            name = “football”;

        }

        public override string getname()

        {

            return name;

        }

        public override string getduration()

        {

            return “four 15 minute quarters”;

        }

    }

}

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

(3)namespace consoleassemblytest//该项目添加了对(1)的引用

{

    class program

    {

        static void main(string[] args)

        {

            assembly assembly = assembly.loadfrom(@”e:\classlibrarysomesports\

bin\debug\classlibrarysomesports.dll”);

            type[] types = assembly.gettypes();

 

            console.writeline(“get type from classlibrarysomesports.dll:”);

            for (int i = 0; i < types.length; i++)

            {

                console.writeline(types[i].name);

            }

 

            //使用getconstructor()方法获取对应类型的构造器,从而构造出该类型的对象

            console.writeline(“use method getconstructor():”);

            constructorinfo ci = types[0].getconstructor(new type[0]);

            classlibrarysport.sport sport = (classlibrarysport.sport)ci.invoke(new object[0]);

            console.writeline(sport.getname() + ” has ” + sport.getduration());

 

            //使用activator.createinstance()方法构造出该类型的对象

//使用assembly.createinstance()返回为null,??

            console.writeline(“use method createinstance():”);

            classlibrarysport.sport sport1 = (classlibrarysport.sport)

activator.createinstance(types[0]);

            console.writeline(sport1.getname() + ” has ” + sport1.getduration());

 

            //反射指定类型中的名称为“getduration”的方法,通过invoke()方法执行该方法

            object objsport = activator.createinstance(types[0]);

            methodinfo method = types[0].getmethod(“getduration”);

            object o = method.invoke(objsport, new object[0]);

            console.writeline(o as string);

 

            console.read();

        }

    }

}

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

output:

get type from classlibrarysomesports.dll:

football

use method getconstructor():

football has four 15 minute quarters

use method createinstance():

football has four 15 minute quarters

four 15 minute quarters

http://www.cnblogs.com/kissknife/archive/2006/08/13/475717.html

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » .NET反射的简单示例-.NET教程,.NET Framework
分享到: 更多 (0)