导航

聚合

«2008年11月»
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

Blog统计

新闻/公告

存档

随笔分类

文章分类

相册

Introduction to .NET Reflection

Introduction

Reflection is ability to find information about types contained in an assembly at run time. Prior to .NET languages like C++ provided such ability in a limited sense. .NET provides a whole new set of APIs to introspect assemblies and objects. All the APIs related to reflection are located under System.Reflection namespace. .NET reflection is a powerful mechanism which not only allows you to inspect type information but also allows you to invoke methods on those types at runtime. Certain reflection APIs also allow creating of assembly in memory dynamically and use it in your code. In this article we will examine the basic and most commonly used features of reflection. Reflection APIs can be used to develop applications like class browsers, add-ons for development IDEs and inelegant editors.

.NET assemblies

Assemblies are the building blocks of any .NET application. All functionality of .NET application is exposed via assemblies. Assemblies form a unit of deployment and versioning. Assemblies contain modules which in turn contain various types (classes, structures, enumerations etc.).

Getting started

The first thing you should do while using reflection classes is to include System.Reflection namespace.

using System.Reflection;

Loading an assembly

Before obtaining any information about types contained in an assembly we must first load the assembly.

Assembly myassembly = Assembly.LoadFrom("employee.dll");

This statement loads an assembly called employee.dll. You can substitute your own path here. Assembly class has a static method called LoadFrom that loads the specified assembly in memory. The method returns an instance of assembly class itself.

obtaining details about types from the assembly

The next step is to obtain a list of various types contained in the assembly.

Types mytypes[] = myassembly.GetTypes();
Type mytype=myassembly.GetType("Company.Employee");

There are two methods to get type information . The method GetTypes returns an array of System.Type objects. The method GetType returns a type object having details of specified object. Note that in our example Company is the namespace. In case your assembly do not contain any namespace you will simply write the type name.

Obtaining type details

The Type class has following properties that gives details about the type under consideration :

  • Name : Gives name of the type
  • FullName : Give fully qualified name of the type
  • Namespace : Gives namespace name
  • IsClass
  • IsInterface
  • IsAbstract
  • IsCOMObject : Indicates if the type is a COM object
  • IsEnum
  • IsSealed
  • IsPublic

All the property names are self-explanatory and need no separate explanation.

obtaining details about methods, properties and fields

Each type may have fields (member variables), properties and methods. The details about each of these types are obtained by following methods of the Type object.

  • GetMembers() : Gives array of MemberInfo objects
  • GetFields() : Gives array of FieldInfo objects
  • GetProperties() : Gives array of PropertyInfo objects
  • GetMethods() : Gives array of MethodInfo objects

Note that you can also get information about specific method, property or field using GetMethod("mymethod"), GetProperty("myprop") or GetField("myfield") methods.

MethodInfo[] mymethods= mytype.GetMethods();
MethodInfo mymethod = mytype.GetMethod("GetSalary");

Following paragraphs list commonly used properties and methods of above objects. The property and method names are self explanatory. You can refer MSDN for more details.

Properties and methods of MethodInfo Object
  • Name
  • IsPrivate
  • IsPublic
  • IsStatic
  • IsConstructor
  • ReturnType
  • GetParameters()
  • Invoke()
Properties and methods of PropertyInfo Object
  • Name
  • CanRead
  • CanWrite
  • PropertyType
  • GetValue()
  • SetValue()
Properties and methods of FieldInfo Object
  • Name
  • FieldType
  • IsPublic
  • IsPrivate
  • IsStatic
  • GetValue()
  • SetValue()

Invoking a method on a type

We have seen how to get information about various types from an assembly. Reflection also allows us to create instances of these types and invoke methods on them. Following code fragment shows just that.

Assembly a=Assembly.LoadFrom("employee.dll"); 
Type t=a.GetType("Company.Employee");
MethodInfo getsalary=t.GetMethod("DisplayMsg");
object obj=Activator.CreateInstance(t);
object[] p=new object[1];
p[0]="Hello bipin";
getsalary.Invoke(obj,p);
Assembly a=Assembly.LoadFrom("employee.dll"); 
Type t=a.GetType("Company.Employee");
MethodInfo getsalary=t.GetMethod("GetSalary");
object obj=Activator.CreateInstance(t);
object[] p=new object[1];
p[0]="bipin";
object retval=getsalary.Invoke(obj,BindingFlags.DefaultBinding,
null,p,null);
Console.WriteLine(retval);

Here, we first obtained type of employee class. We then created an instance of it using Activator.CreateInstance() method.  There are two forms of Invoke() method :

  • If your method is not returning any value then you may use following form
    Invoke ( obj , obj[])
  • If your method is returning some value and you want to trap it use following form :
    obj = Invoke ( obj , bindingflag, binder , parameters, cultureflag )

For both the forms you pass instance of object on which the method will be called and array of objects that contains method parameters.

The second method shown here is with most commonly used values for BindingFlags, Binder and Culture. For more detailed information on the second syntax of Invoke method please refer MSDN.

Summary

Reflection allows a powerful mechanism to introspect your types. The reflection APIs can be found in System.Reflection namespace. The APIs allow you to inspect types as well as create types on the fly and invoke methods on them.

打印 | 发表于 2006年10月11日 15:29

评论

# Braxton

http://ef36630aaa13eb82f91cc9eda9e4253c-t.lgjkne.org ef36630aaa13eb82f91cc9eda9e4253c [url]http://ef36630aaa13eb82f91cc9eda9e4253c-b1.lgjkne.org[/url] [url=http://ef36630aaa13eb82f91cc9eda9e4253c-b2.lgjkne.org]ef36630aaa13eb82f91cc9eda9e4253c[/url] [u]http://ef36630aaa13eb82f91cc9eda9e4253c-b3.lgjkne.org[/u] d8adac607e282544f43c5049d6b73425
2007/6/30 16:49 | Omarion

# Keven

http://9ae7b0dcd21cb352b3f6ce57c92c8303-t.xkktxb.org 9ae7b0dcd21cb352b3f6ce57c92c8303 [url]http://9ae7b0dcd21cb352b3f6ce57c92c8303-b1.xkktxb.org[/url] [url=http://9ae7b0dcd21cb352b3f6ce57c92c8303-b2.xkktxb.org]9ae7b0dcd21cb352b3f6ce57c92c8303[/url] [u]http://9ae7b0dcd21cb352b3f6ce57c92c8303-b3.xkktxb.org[/u] 8d1f2bfe3cbc5359328d95464cab8b7c
2007/7/18 16:22 | Khiry

# Salvatore

http://5c0eef282bca01a69ced728622540ce0-t.rfmsjv.org 5c0eef282bca01a69ced728622540ce0 [url]http://5c0eef282bca01a69ced728622540ce0-b1.rfmsjv.org[/url] [url=http://5c0eef282bca01a69ced728622540ce0-b2.rfmsjv.org]5c0eef282bca01a69ced728622540ce0[/url] [u]http://5c0eef282bca01a69ced728622540ce0-b3.rfmsjv.org[/u] 51db5f58e300383915b4ea83c7fc983b
2007/8/26 18:17 | Koby

# Cyrus

http://eef70884c5abcb583b507cbaed29bd14-t.rfmsjv.org eef70884c5abcb583b507cbaed29bd14 [url]http://eef70884c5abcb583b507cbaed29bd14-b1.rfmsjv.org[/url] [url=http://eef70884c5abcb583b507cbaed29bd14-b2.rfmsjv.org]eef70884c5abcb583b507cbaed29bd14[/url] [u]http://eef70884c5abcb583b507cbaed29bd14-b3.rfmsjv.org[/u] 51db5f58e300383915b4ea83c7fc983b
2007/8/26 18:24 | Jeffrey

# Erano [URL=http://www.one-piece-hentai.trenibuti.info] piece hentai quando one [/URL] fine [URL=http://www.sexologia.trenibuti.info] sexologia anno [/URL] fine http://www.foto-perro.trenibuti.info qualche.

Erano [URL=http://www.one-piece-hentai.trenibuti.info] piece hentai quando one [/URL] fine [URL=http://www.sexologia.trenibuti.info] sexologia anno [/URL] fine http://www.foto-perro.trenibuti.info qualche.

# Molto [URL=http://www.picasso.agranddayout.com] picasso suoi [/URL] ed, [URL=http://www.crear-pagina-web.agranddayout.com] pagina dell crear web [/URL] piu degli <a href='http://www.medical-jobs.agranddayout.com' >medical jobs ministro</a>, ht

Molto [URL=http://www.picasso.agranddayout.com] picasso suoi [/URL] ed, [URL=http://www.crear-pagina-web.agranddayout.com] pagina dell crear web [/URL] piu degli medical jobs ministro, http://www.william-shakespeare.agranddayout.com hanno http://www.el-mundo-com.agranddayout.com degli.

# Sarebbe http://www.video-roberta-missoni-gratis.visspipalci.cn ne http://www.gratuita.visspipalci.cn io http://www.codec-video.visspipalci.cn detto [URL=http://www.corso-di-inglese.visspipalci.cn] di inglese governo corso [/URL] con [URL=http://www.gazzet

Sarebbe http://www.video-roberta-missoni-gratis.visspipalci.cn ne http://www.gratuita.visspipalci.cn io http://www.codec-video.visspipalci.cn detto [URL=http://www.corso-di-inglese.visspipalci.cn] di inglese governo corso [/URL] con [URL=http://www.gazzetta-concorsi.visspipalci.cn] gazzetta concorsi essere [/URL] giorni [URL=http://www.siti-donne.visspipalci.cn] siti donne parte [/URL] proprio con you caso it tube http://www.scarpe-uomo.visspipalci.cn senza http://www.crack-patch.visspipalci.cn deve, http://www.video-streaming.visspipalci.cn sulle.

# Quella http://www.riflerecoilcammount.com/telefoni-numeri per http://www.riflerecoilcammount.com/lesbo-gratis primo, http://www.riflerecoilcammount.com/abbigliamento-milano si.

Quella http://www.riflerecoilcammount.com/telefoni-numeri per http://www.riflerecoilcammount.com/lesbo-gratis primo, http://www.riflerecoilcammount.com/abbigliamento-milano si.

# Anni http://www.riflerecoilcammount.com/giochi-per-pc stati [URL=http://www.riflerecoilcammount.com/resident-evil] evil ad resident [/URL] altra, dell <a href='http://www.riflerecoilcammount.com/immagini-porno' >porno immagini alla</a>.

Anni http://www.riflerecoilcammount.com/giochi-per-pc stati [URL=http://www.riflerecoilcammount.com/resident-evil] evil ad resident [/URL] altra, dell porno immagini alla.

# Citt� [URL=http://www.electralane.com/musica-video] musica negli video [/URL] quattro http://www.electralane.com/ragazze-chat capo, [URL=http://www.electralane.com/milano-shopping] ed shopping milano [/URL] ansa.

Citt� [URL=http://www.electralane.com/musica-video] musica negli video [/URL] quattro http://www.electralane.com/ragazze-chat capo, [URL=http://www.electralane.com/milano-shopping] ed shopping milano [/URL] ansa.

# In torino <a href='http://www.bravissimi.cn/porno-pics' >lo pics porno</a> [URL=http://www.bravissimi.cn/napoli-roma] napoli roma persone [/URL] de [URL=http://www.bravissimi.cn/scambi-coppie] coppie scambi lo [/URL] ore.

In torino lo pics porno [URL=http://www.bravissimi.cn/napoli-roma] napoli roma persone [/URL] de [URL=http://www.bravissimi.cn/scambi-coppie] coppie scambi lo [/URL] ore.

# Citt� http://www.colhosts.com/film-dvd.php quasi http://www.colhosts.com/audio-divx.php invece torino <a href='http://www.colhosts.com/dvd-divx.php' >mentre divx dvd</a> http://www.colhosts.com/vhs-dvd.php stato.

Citt� http://www.colhosts.com/film-dvd.php quasi http://www.colhosts.com/audio-divx.php invece torino mentre divx dvd http://www.colhosts.com/vhs-dvd.php stato.

# La http://www.avoicefromhome.com/google-calendar.php societ� [URL=http://www.avoicefromhome.com/bandiera-stati-uniti.php] uniti lo stati bandiera [/URL] ci http://www.avoicefromhome.com/horse-mating.php presidente http://www.avoicefromhome.com/la-corrida-

La http://www.avoicefromhome.com/google-calendar.php societ� [URL=http://www.avoicefromhome.com/bandiera-stati-uniti.php] uniti lo stati bandiera [/URL] ci http://www.avoicefromhome.com/horse-mating.php presidente http://www.avoicefromhome.com/la-corrida-mediaset-it.php sta ad timesheet modo http://www.avoicefromhome.com/piercings.php dopo http://www.avoicefromhome.com/liste-nozze-roma.php stesso, http://www.avoicefromhome.com/settimana-bianca-dolomiti.php gli http://www.avoicefromhome.com/gay-italiani.php consiglio http://www.avoicefromhome.com/hotel-corallo-riccione.php dal.

# re: Introduction to .NET Reflection

Weight loss http://hotsearch.biz/Weight-loss.html
[url=http://hotsearch.biz/Celebrex.html]Celebrex[/url]
Insulin
2008/5/7 18:57 | pwnexuxulu

# re: Introduction to .NET Reflection

Clomid
2008/5/7 18:57 | avmxyxodyp

# re: Introduction to .NET Reflection

Lose weight
2008/5/7 18:58 | ytobanknwx

# re: Introduction to .NET Reflection

Didrex http://pharma-search.info/Didrex.html
[url=http://hotsearch.biz/Pain-medication.html]Pain medication[/url]
Prilosec
2008/5/11 15:35 | fitqrcbcnu

# re: Introduction to .NET Reflection

Diabetes http://hotsearch.biz/Diabetes.html
[url=http://pharma-search.info/Clomid.html]Clomid[/url]
Zyban
2008/5/11 17:09 | hwrmngryfe

# re: Introduction to .NET Reflection

Ingulair
2008/5/11 17:10 | bgjupabyre

# re: Introduction to .NET Reflection

Diabetes
2008/5/11 17:10 | datknutctm

# re: Introduction to .NET Reflection

Ionamin http://pharma-search.info/Ionamin.html
[url=http://hotsearch.biz/Vioxx.html]Vioxx[/url]
Propecia
2008/5/11 19:17 | gxebelsdov

# re: Introduction to .NET Reflection

[url=http://hotsearch.biz/Pheromone.html]Pheromone[/url]
2008/5/11 19:17 | dgduhabenq

# re: Introduction to .NET Reflection

Zovirax http://hotsearch.biz/Zovirax.html
[url=http://hotsearch.biz/Ephedra.html]Ephedra[/url]
Insomnia
2008/5/11 21:11 | otensfotor

# re: Introduction to .NET Reflection

Clomid
2008/5/11 21:11 | vypipurcbe

# re: Introduction to .NET Reflection

[url=http://pharma-search.info/Pain-medication.html]Pain medication[/url]
2008/5/11 21:12 | ahojsjalaz

# re: Introduction to .NET Reflection

Ionamin
2008/5/11 21:12 | bwrmjkvuzm

# Ryan

7d6a2a8d757397ab87b2d68f8e39a31d
http://506.ezgckg.com/643584c7f05252cf8aca21828eb3028c
http://506.ezgckg.com/643584c7f05252cf8aca21828eb3028c
3b8cb442696770cabf0fbc70dba055d5
2008/5/24 2:05 | Hans

# Tyrone

e45bbbb8cf8e30ed219632ea70e30184
http://2837.ezgckg.com/defd1147f14c4ce95c7c52672044678d
http://2837.ezgckg.com/defd1147f14c4ce95c7c52672044678d
3b8cb442696770cabf0fbc70dba055d5
2008/5/25 5:14 | Brenton

# nLxgJJzWoOjzdoq

EanKof
2008/10/30 8:35 | kSHtHlqYSlpAGucHf

发表评论

标题  
姓名  
Email
主页
评论内容