Reflection n Leveraging the Power of Metadata Objectives
Reflection n Leveraging the Power of Metadata
Objectives n Provide n Explain an introduction to. NET Reflection how applications can use Reflection to explore type information and how they can build types at runtime
Contents n Section 1: Overview n Section 2: Exploring Metadata n Section 3: Detail Information n Section 4: Building Types at Runtime n Section 5: Putting it together n Summary
Section 1: Overview n Looking n What's n. NET back: Automation and COM Type Info wrong with that? Reflection Core Concepts
Looking Back: Automation n Type. Libraries n contain type information Exploration through IType. Lib/IType. Info n Attributes describe behavior of elements n e. g. Directionality of parameters n e. g. Method role (instance method, property) n Dynamic n Type Invocation using IDispatch system supports most popular simple types n Dynamic types using VARIANT n Arrays passed using SAFEARRAY n Strings expressed as BSTR
What's wrong with that? n Automation client model favors Visual. Basic n Automation server model favors C/C++ n IType. Info and IDispatch are way too complicated n Information n No model is limited sufficient support for complex types n SAFEARRAYs n BSTRs n Type are a pain from C/C++ are difficult to manage from C/C++ information separate from code
. NET Reflection Core Concepts n Metadata n Single location for type information and code n Code is literally contained within type information n Every. NET object can be queried for its type n Types' metadata can be explored with Reflection n Dynamic Type System n Highly dynamic and language independent n Types may be extended and built at run-time n Allows on-the-fly creation of assemblies n . NET Compilers use. NET to emit. NET code
Section 2: Exploring Metadata n Who are you? n What are you? n Anything n Now special about you? tell me what you have! n Types and Instances
Meta. Data: Type Info at Runtime System. Type Attributes Events Fields Properties Constructors Parameters Methods [serializable] public class Person : { public event On. Save. Change onsv; public Date DOB; public string First. Name; public string Last. Name; public string Name { get { return First. Name + " " + Last. Name; } } public void Person(string First, string Last) { First. Name=First; Last. Name=Last; } public bool Save() { System. Type t = this. Get. Type(); foreach( Field. Info f in t. Get. Fields() ) {. . . } }
Who are you? n Accessing meta-data: System. Object. Get. Type() n All. NET classes (implicitly) inherit System. Object n Available on every. NET class; simple types too n Explicit language support for type meta-data n C#, JScript. NET: typeof(…) n VB. NET: n Determining If Type. Of … Is … Then … Type Identity n Types have unique identity across any assembly n Types can be compared for identity n if ( a. Get. Type() == b. Get. Type() ) { … };
System. Type n Access to meta-data for any. NET type n Returned n Allows by System. Object. Get. Type() drilling down into all facets of a type n Category: Simple, Enum, Struct or Class n Methods and Constructors, Parameters and Return n Fields and Properties, Arguments and Attributes n Events, Delegates and Namespaces
What are you? n Value, n Interface or Class? Is. Value. Type, Is. Interface, Is. Class n Public, n Private or Sealed ? Is. Not. Public, Is. Sealed n Abstract n or Implementation? Is. Abstract n Covers n Very all possible properties of a managed type intuitive API, no "Parameter Hell"
Anything special about you? n Special Memory Layout? n Is. Auto. Layout n Is. Explicit. Layout n Is. Layout. Sequential n COM n Objects? Is. COMObject n More… n Is. Unicode. Class n Is. Special. Name, etc.
Now tell me what you have! n Finding n and Exploring Members Member. Info: Get. Members(), Find. Members() n Exploring n Field. Info: Get. Fields(), Property. Info: Get. Properties() n Exploring n Fields and Properties Constructors, Methods and Events Get. Constructors(), Get. Methods(), Get. Events() n Exploring attributes, determining implemented interfaces, enumerating nested types, … n Summary: Everything you may ever want to know
Type and Instances n Type Safety First! Type checking at runtime n C#: if ( o is Customer ) { … } n VB: If Type. Of o Is Customer Then … End If n Dynamic n Invocation through Reflection Support for late binding n Method. Info. Invoke() n Field. Info. Set. Value() n Property. Info. Set. Value()
Section 3: Detail Information n Member. Info n Field. Info, Property. Info n Constructor. Info, Method. Info
Member. Info n Base n class for all "member" element descriptions Fields, Properties, Methods, etc. n Provides member kind, name and declaring class Member. Info Method. Base Parameter. Info Method. Info Constructor. Info Field. Info Event. Info Property. Info
Field. Info, Property. Info n Field data type and attributes n Static or Instance field, protection level n Can set value through reflection n Provides low-level, direct access with Set. Value. Direct() n Property. Info n Property type and attributes n Test methods for readability, writeability n "get" and "set" Method. Info n Indexer Parameter. Info n Can invoke "set" and "get" through Reflection
Method. Info, Constructor. Info n Method. Info n Return type and attributes n List of all parameters as Parameter. Info array n Detail implementation information through flag-field n Can invoke method through Reflection n Constructor. Info n Same features as Method. Info, just for constructors
Attributes n Custom attributes are the killer-app for Reflection! n Attributes enable declarative behavior n Attributes allow data augmentation [dbcolumn("Address 1")] string Street; [dbcolumn("Postcode")] string ZIP; Mark class as serializable Type. Get. Custom. Attributes() [serializable] class Person {. . . Map fields to database columns with Field. Info. Get. Custom. Attributes()
The Bigger picture n Types know their Module, Modules know their types n Modules n Code know their Assembly and vice versa can browse and search its entire context Assembly Module Class Constructor Method Field Module Struct Delegate Class Interface
The Unmanaged Spy: Metadata API n Unmanaged n Used n Full by Visual. Studio. NET and Compilers Access to all Reflection Information for Tools n Fully documented in the "Tool Developer's Guide" n Buddy: n (COM) Version of Reflection Assembly Metadata API Reads/writes Assembly Manifests
Section 4: Building Types at Runtime n Introducing n Why? System. Reflection. Emit Some scenarios n Dynamic Modules and Assemblies n Creating Types and Classes n Writing IL
Introducing System. Reflection. Emit n Full representation of physical structure n Allows building modules and assemblies at runtime n Transient code only used at runtime n Persistent code for reuse n Create n Used classes, types and emit IL by. NET compilers to build. NET apps
Why? Some Scenarios… n Build n classes dynamically from script-like code ASP. NET, Regular Expressions do just that ! n Generate n e. g. build interfaces, base classes from UML n Create dynamic wrappers for existing code n Transfer n code from visual development tools code-chunks to remote machines Distributed processing scenarios (like SETI@home)
Building Assemblies n System. Reflection. Emit. Assembly. Builder n Dynamically create new assemblies n Create manifest and resources n Add modules n Specify security requirements n Can n Act be persisted as files or held in memory and behave like any other assembly
Building Modules n System. Reflection. Emit. Module. Builder n Modules n Allows contain types, classes and code creating fully functional modules with code n Can associate source code n Emit debug symbols n Acts like any module created by any. NET compiler
Writing IL n Emit accepts IL (Intermediate Language) code n Same n IL code as emitted by C#, VB. NET, Eiffel# is optimized and translated into machine code n Reflection. Emit puts you "on-par" n Same backend as. NET compilers n Same access to code-generation n Languages are mostly scanners and parsers n For more info see System. Code. DOM
Section 5: Putting It Together n Visual. Studio. NET n What and Reflection ASP+ really does with a page
Visual. Studio. NET and Reflection Toolbox Component Class Description Default. Value Properties Window Help Localizable Read. Only Component. Model Attributes Designers Help
What ASP. NET does with a Page IIS ASP. NET runtime file exists? assembly exists, 2 same timestamp? 1 2 a 3 no? compile <%Page codebehind="pg"%> <html> <body> <asp: label/> <asp: textbox/> </html> </body> run ASP. NET compiler Reflection class pg : Page {. . . } Page Assembly
Summary n Reflection = System. Type + Get. Type() n Explore Type Information at Runtime n Enables Attribute-Driven Programming n Use Emit Classes to Produce. NET Assemblies n Bottom Line: Fully Self-Contained Structural Model
Questions?
- Slides: 33