understanding reflection
TRANSCRIPT
![Page 1: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/1.jpg)
![Page 2: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/2.jpg)
2
Understanding Reflection
Session Code: DVP307
Tamir KhasonTechnology Consultor¹mPrest Systemshttp://blogs.microsoft.co.il/blogs/tamir
¹con·sul·tor (kən sult′ər) - one of a group of priests appointed to advise and assist a bishop
![Page 3: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/3.jpg)
3
ExecutionExecution
CompilationCompilation
CLR – compilation and execution
3
Source codeSource codeLanguage Language compilercompiler
JIT compilerJIT compiler
Before installation Before installation or the first time or the first time each method is each method is
calledcalled
MSILMSIL
MetadataMetadata
CodeCode
Native codeNative code
![Page 4: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/4.jpg)
4
Reflection overview
All types in the CLR are self-describing CLR provides a reader and writer for type definitions
System.Reflection & System.Reflection.emitYou can ‘read’ programs You can map between type systems You can interrogate objects and types inside a running program
![Page 5: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/5.jpg)
5
What is “Reflection”?
“Reflection provides objects that encapsulate assemblies, modules, and types.” (MSDN)
“You can use reflection to dynamically create an instance of a type...” (MSDN)
“You can then invoke the type's methods or access its fields and properties.” (MSDN)
“Reflection.Emit namespace contains classes that allow a compiler or tool to emit metadata and Microsoft intermediate language (MSIL)” (MSDN)
![Page 6: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/6.jpg)
6
Where is “Reflection”?
System.Reflection namespace contains most Reflection classes.
System.Type is Reflection class used to access type metadata.
…more…
![Page 7: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/7.jpg)
7
How to “Reflection”?
Viewing metadata
Performing type discovery
Late binding to methods and properties (Dynamic Invocation)
Creating types at runtime (Reflection Emit)
![Page 8: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/8.jpg)
8
How to… perform type discovery
You can use reflection to explore and examine the contents of an assembly programmatically You can find
methods, fields, properties, and events associated with a typesignatures of each of the type's methods;interfaces supported by the type; type's base class.…
![Page 9: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/9.jpg)
9
What are you?
Value, Interface or Class?IsValueType, IsInterface, IsClass
Public, Private or Sealed ?IsNotPublic, IsSealed
Abstract or Implementation?IsAbstract
![Page 10: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/10.jpg)
10
What you have?
Finding and Exploring MembersMemberInfo: GetMembers(), FindMembers()
Exploring Fields and PropertiesFieldInfo: GetFields(), PropertyInfo: GetProperties()
Exploring Constructors, Methods and EventsGetConstructors(), GetMethods(), GetEvents()
Exploring attributes, determining implemented interfaces, enumerating nested types, …
Everything you may ever want to know
![Page 11: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/11.jpg)
11
MemberInfo
Base class for all "member" element descriptions
Fields, Properties, Methods, etc.
Provides member kind, name and declaring class
MemberInfo
MethodBase ParameterInfo FieldInfo EventInfo PropertyInfo
MethodInfo ConstructorInfo
![Page 12: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/12.jpg)
12
MethodInfo vs. ConstructorInfo
MethodInfoReturn type and attributesList of all parameters as ParameterInfo arrayDetail implementation information through flag-fieldCan invoke method through Reflection
ConstructorInfoSame features as MethodInfo, just for constructors
![Page 13: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/13.jpg)
13
FieldInfo vs. PropertyInfo
FieldInfoField data type and attributesStatic or Instance field, protection levelCan set value through reflection
Provides low-level, direct access with SetValueDirect()
PropertyInfoProperty type and attributesTest methods for readability, writeability"get" and "set" MethodInfoIndexer ParameterInfoCan invoke "set" and "get" through Reflection
![Page 14: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/14.jpg)
14
We can clone it…Unknown object
GetType().GetMembers()
For Each MemberFieldInfo.Copy old value to new
Object
Type kidType = oldKid.GetType();
Kid newKid = new Kid();
foreach (var m in kidType.GetProperties()) { m.SetValue(newKid ,
m.GetValue(oldKid, null), null); }
![Page 15: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/15.jpg)
15
Clone optimizationUnknown object
GetType().GetMembers()
For Each MemberCreate Code that copies members
Save as Method for later Invocation
Kid CloneKid(Kid){
newKid.Height = oldKid.Height newKid.Weight = oldKid.Weight
}
![Page 16: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/16.jpg)
16
Clone optimized
Unknown object
Has custom
method?ExecuteYesYesCopy Members NoNo
![Page 17: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/17.jpg)
17
What is… attributes
An attribute is an object that represents data you want to associate with an element in your program.
Two Kinds of Attributes:Intrinsic: Supplied as part of the Common Language Runtime (CLR)Custom: Attributes you create for your own purposes
![Page 18: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/18.jpg)
18
Code generation
Using Dynamic InvokeCreate and compile source code in runtimePersistent in diskInvoke Compiler to generate IL
Using Reflection EmitEmit IL code directlyTemporarily stored in memoryBetter performance
Kid CloneKid(Kid){
newKid.Height = oldKid.Height newKid.Weight = oldKid.Weight
}
![Page 19: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/19.jpg)
19
![Page 20: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/20.jpg)
20
CodeDOMCodeEntryPointMethod start = new CodeEntryPointMethod();
CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Hello World!") );
start.Statements.Add(cs1);
public static void Main(){
System.Console.WriteLine(“Hello World!”);}
![Page 21: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/21.jpg)
21
CodeDOM
CodeArgumentReferenceExpressionCodeArrayCreateExpressionCodeArrayIndexerExpressionCodeAssignStatementCodeAttachEventStatementCodeAttributeArgumentCodeAttributeArgumentCollectionCodeAttributeDeclarationCodeAttributeDeclarationCollectionCodeBaseReferenceExpressionCodeBinaryOperatorExpressionCodeCastExpressionCodeCatchClauseCodeCatchClauseCollectionCodeCommentCodeCommentStatementCodeCommentStatementCollectionCodeCompileUnitCodeConditionStatementCodeConstructorCodeDelegateCreateExpression
CodeExpressionCollectionCodeExpressionStatementCodeFieldReferenceExpressionCodeGotoStatementCodeIndexerExpressionCodeIterationStatementCodeLabeledStatementCodeLinePragmaCodeMemberEventCodeMemberFieldCodeMemberMethodCodeMemberPropertyCodeMethodInvokeExpressionCodeMethodReferenceExpressionCodeMethodReturnStatementCodeNamespaceCodeNamespaceCollectionCodeNamespaceImportCodeNamesapceImportCollectionCodeObjectCodeObjectCreateExpression
![Page 22: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/22.jpg)
22
CodeDOM – even moreCodeCompilerCodeDomProviderCodeGeneratorCodeGeneratorOptionsCodeParserCompilerErrorCompilerErrorCollectionCompilerParametersCompilerResultsExecutorIndentedTextWriterTempFileCollection
ICodeCompilerICodeGeneratorICodeParser
CodeBinaryOperatorTypeFieldDirectionMemberAttributes
CodePropertySetValueReferenceExpressionCodeRemoveEventStatementCodeSnippetCompileUnitCodeSnippetExpressionCodeTypeMemberCollectionCodeTypeOfExpressionCodeTypeReferenceCodeTypeReferenceCollectionCodeTypeReferenceExpressionCodeVariableDeclarationStatementCodeVariableReferenceExpression
CodeCatchClauseCodeCatchClauseCollectionCodeCommentCodeCommentStatementCodeCommentStatementCollectionCodeCompileUnitCodeConditionStatementCodeConstructorCodeDelegateCreateExpressionCodeDelegateInvokeExpressionCodeDirectionExpressionCodeEntryPointMethod
CodeEventReferenceExpressionCodeExpressionCodeSnippetStatementCodeSnippetTypeMemberCodeStatementCollectionCodeThisReferenceExpressionCodeThrowExceptionStatementCodeTryCatchFinallyStatementCodeTypeConstructorCodeTypeDeclarationCodeTypeDeclarationCollectionCodeTypeDelegateCodeTypeMember
![Page 23: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/23.jpg)
23
•Dynamic Invocation with Brut force Dynamic Invocation with Brut force compilationcompilation
•Dynamic Invocation with Brut force Dynamic Invocation with Brut force CodeDOMCodeDOM•Dynamic Invocation with CodeDOMDynamic Invocation with CodeDOM
![Page 24: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/24.jpg)
24
CodeDOM – Bottom line
A lot of goodies, but very complicated yet limited
…also you can write your ownCodeDomProvider
…however, if you can generate the CodeDom, it does not mean you can generate code with it
![Page 25: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/25.jpg)
25
![Page 26: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/26.jpg)
26
IL introduction
IL – The language for executionIndependent of CPU and platform
Created by Microsoft, external commercial and academic language/compiler writers
Stack based virtual machine:5 + 10 - 3 5 + 10 - 3
IL_0001: ldc.i4 5IL_0001: ldc.i4 5 IL_0002: ldc.i4 10 IL_0002: ldc.i4 10 IL_0003: addIL_0003: add IL_0004: ldc.i4 3IL_0004: ldc.i4 3 IL_0005: subIL_0005: sub Evaluation StackEvaluation Stack
0000 0050000 005
0000 00100000 0010
0000 00150000 0015
0000 00030000 0003
0000 00120000 0012
![Page 27: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/27.jpg)
27
IL introduction
IL storage opcodesLocals of a method
Fields in a class
string str = “Hello, World!”string str = “Hello, World!” IL_0001: ldstr “Hello, World!”IL_0001: ldstr “Hello, World!” IL_0002: stloc strIL_0002: stloc str IL_0003: ldloc str IL_0003: ldloc str
Foo.f = “Hello, World!”Foo.f = “Hello, World!” IL_0001: ldstr “Hello, World!”IL_0001: ldstr “Hello, World!” IL_0002: stfld string Foo::fIL_0002: stfld string Foo::f IL_0003: ldfld string Foo::fIL_0003: ldfld string Foo::f
![Page 28: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/28.jpg)
28
IL introduction
IL control flow opcodesif (b) { ... } else { ... } if (b) { ... } else { ... }
IL_0001: ldloc bIL_0001: ldloc b IL_0002: ldc.i4.1IL_0002: ldc.i4.1 IL_0003: ceqIL_0003: ceq IL_0004: brfalse IL_00020IL_0004: brfalse IL_00020 // if true statements// if true statements IL_0010: ...IL_0010: ... IL_0011: br IL_00025IL_0011: br IL_00025 // else statements// else statements IL_0020: ...IL_0020: ... // rest of method// rest of method IL_0025: ...IL_0025: ...
![Page 29: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/29.jpg)
29
Reflection.Emit
AssemblybuilderConstructorBuilderCustomAttributeBuilderEnumBuilderEventBuilderFieldBuilderILGenerator
Label LocalBuilder MethodBuilder ModuleBuilder ParameterBuilder PropertyBuilder TypeBuilder
![Page 30: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/30.jpg)
30
Code Emittingpublic class MyClass {
public static void Main() {string str = “Hello World!”;Console.WriteLine (str);
}}
AssemblyBuilderAssemblyBuilder
ModuleBuilderModuleBuilder
TypeBuilderTypeBuilder
MethodBuilderMethodBuilder
LocalBuilderLocalBuilder
ILGeneratorILGeneratorOPCodesOPCodes
![Page 31: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/31.jpg)
31
Lightweight Code Generation
DynamicMethod
Kid CloneKid(Kid){
newKid.Height = oldKid.Height newKid.Weight = oldKid.Weight
}
DynamicMethodDynamicMethodILGeneratorILGeneratorOPCodesOPCodes
![Page 32: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/32.jpg)
32
•Dynamic Invocation with EmitDynamic Invocation with Emit
![Page 33: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/33.jpg)
33
![Page 34: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/34.jpg)
34
HackMe
All types in the CLR are self-describing
DynamicMethod dm =…dm.GetMethodBody().GetILAsByteArray();
MethodInfo mi = ..mi.GetMethodBody().GetILAsByteArray();
![Page 35: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/35.jpg)
35
What's new in .NET 3.5?
Lambdas.Compile() for code generation
Expression TreesParse and understand
![Page 36: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/36.jpg)
36
From delegate to LambdaDelegate void SomeDelegate(EventsArgs e);
Object.SomeEvent += new SomeDelegate(SomeMethod);
DelegateDelegate
Object.SomeEvent += delegate(EventArgs e) { //work here }
Anonymous delegate Anonymous delegate
Object.SomeEvent += (e) => { //work here };LambdaLambda
![Page 37: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/37.jpg)
37
Expression Tree
Use Expression<T>
Parse Lambdas at runtime
Compile at runtime (Expression.Compile())
Use the Expression Tree Debug Visualizerhttp://code.msdn.microsoft.com/csharpsamples
![Page 38: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/38.jpg)
38
•Parse and visualize treesParse and visualize trees •Compile LambdasCompile Lambdas
![Page 39: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/39.jpg)
Related Content
TodayToday
14:45 – Team Foundation Server – Brian Randell – Session room 0614:45 – Team Foundation Server – Brian Randell – Session room 06
16:45 – Data Protection with CryptoAPI – Rafael Lukawiecki – Session room 0616:45 – Data Protection with CryptoAPI – Rafael Lukawiecki – Session room 06or Optimizing your WPF application by me – Session room 09or Optimizing your WPF application by me – Session room 09
19:30 – BEACH PARTY!19:30 – BEACH PARTY!
TomorrowTomorrow
9:00 – Best Practicies for the VB.NET and C# – Lisa Feigenbaum – Session room 079:00 – Best Practicies for the VB.NET and C# – Lisa Feigenbaum – Session room 07
10:15 – Making your test lab obsolete – Brian Randell – Session room 0710:15 – Making your test lab obsolete – Brian Randell – Session room 07
![Page 40: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/40.jpg)
40
Resources
www.microsoft.com/teched Tech·Talks Tech·Ed BloggersLive Simulcasts Virtual Labs
http://microsoft.com/technet
Evaluation licenses, pre-released products, and MORE!
http://microsoft.com/msdn
Developer’s Kit, Licenses, and MORE!
![Page 41: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/41.jpg)
41
Please Please complete ancomplete anevaluationevaluation
![Page 42: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/42.jpg)
42
![Page 43: Understanding Reflection](https://reader038.vdocuments.net/reader038/viewer/2022102716/554ebd23b4c905064d8b467b/html5/thumbnails/43.jpg)
43
© 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS,
IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.