Reflection in.Net Siun-Wai Seow. Objective Explain.NET Reflection When to use it? How to use it?...

Preview:

Citation preview

Reflection in .Net

Siun-Wai Seow

Objective

• Explain .NET Reflection

• When to use it?

• How to use it?

• Topic is in the final exam

Overview

• Reflection• .Net Execution Model• Show how applications can use Reflection to

explore type information and how they can build types at runtime

• Demo for each sub-topic

What is Reflection

• A way to acquire important information at run time about the assemblies it loads.

Uses of Reflection

• Viewing metadata (Attributes)

• Performing type discovery

• Late binding to methods and properties

• Dynamic Loading/Creating types at runtime (Reflection Emit)

• How is it done?

.Net Execution Model

Cobol VB C++ C#

CIL code(+ metadata)

Loader/verifierLoader/verifier

Managed Code

Uncompiledmethod call

ExecutionExecution

Language compilersLanguage compilers

.NET languages

JIT compilerJIT compiler

Metadata

• Metadata– Single location for type information and code– Types' metadata can be explored with

Reflection– Code is literally contained within type

information– Every .NET object can be queried for its type

Uses of Metadata

• Dynamic Type System– Allows on-the-fly creation of assemblies– .NET Compilers use .NET to emit .NET code

MetaData: Type Info at Runtime[serializable]public class Person : { public event OnSaveChange onsv; public Date DOB; public string FirstName; public string LastName; public string Name { get { return FirstName + " " + LastName; } } public Person(string First,string Last) { FirstName=First;LastName=Last; } public bool Save() { System.Type t = this.GetType(); foreach( FieldInfo f in t.GetFields() ) { ... } }

System.Type

Attributes

Fields

Properties

Constructors

Methods

Events

Parameters

Viewing metadata

• Add custom attributes to a compiled executable’s metadata

• Why/When to use this?

Scenario

• Suppose that your organization wants to keep track of bug fixes. You already keep a database of all your bugs, but you'd like to tie your bug reports to the fixes in the code.

• How do implement this?

• [BugFixAttribute(121, "Jesse Liberty", "01/03/05")]• [BugFixAttribute(107, "Jesse Liberty", "01/04/05", Comment = "Fixed off by one errors")]• public class MyMath• {• ……………………• }

• [AttributeUsage(AttributeTargets.Class |• AttributeTargets.Constructor |• AttributeTargets.Field |• AttributeTargets.Method |• AttributeTargets.Property,• AllowMultiple = true)]• public class BugFixAttribute : System.Attribute• {• …………………• }

• public static void Main()• { ………………..• object[] attributes;• attributes = inf.GetCustomAttributes(typeof(BugFixAttribute), false);

• // iterate through the attributes, retrieving the • // properties• foreach (Object attribute in attributes)• {• BugFixAttribute bfa = (BugFixAttribute)attribute;• Console.WriteLine("\nBugID: {0}", bfa.BugID);• Console.WriteLine("Programmer: {0}", bfa.Programmer);• Console.WriteLine("Date: {0}", bfa.Date);• Console.WriteLine("Comment: {0}", bfa.Comment);• }• }

Demo1

• demo1.doc• Project Programming_Csharp

Performing type discovery

• This allows you to examine the types in an assembly.

• Project Programming_Csharp2

Reflecting on an assembly • using System;• using System.Reflection;

• public class Tester• {• //Reflecting on an assembly• public static void Main()• {• // what is in the assembly• Assembly a = Assembly.Load("Mscorlib.dll");• Type[] types = a.GetTypes();• foreach (Type t in types)• {• Console.WriteLine("Type is {0}", t);• }• Console.WriteLine(• "{0} types found", types.Length);• }• }

Reflecting on a Type

• public static void Main()• {• // examine a single object• Type theType =• Type.GetType(• "System.Reflection.Assembly");• Console.WriteLine(• "\nSingle Type is {0}\n", theType);• }

Reflecting on the members of a type

• public static void Main()• {• // examine a single object• Type theType =• Type.GetType(• "System.Reflection.Assembly");• Console.WriteLine(• "\nSingle Type is {0}\n", theType);

• // get all the members• MemberInfo[] mbrInfoArray =• theType.GetMembers();• foreach (MemberInfo mbrInfo in mbrInfoArray)• {• Console.WriteLine("{0} is a {1}",• mbrInfo, mbrInfo.MemberType);• }• }

Finding type methods

• public static void Main()• {• // examine a single object• Type theType =• Type.GetType(• "System.Reflection.Assembly");• Console.WriteLine(• "\nSingle Type is {0}\n", theType);

• MemberInfo[] mbrInfoArray = theType.GetMethods();

• foreach (MemberInfo mbrInfo in mbrInfoArray)• {• Console.WriteLine("{0} is a {1}",• mbrInfo, mbrInfo.MemberType);• }• }

Late binding to methods and properties

• Performing late binding by dynamically instantiating and invoking methods on types.

• Done in homework 3 (application domain/stack walk/permission).

Creating types at runtime

• The ultimate use of reflection is to create new objects/types at runtime and then to use those objects to perform tasks. You might do this when a new class, created at runtime, will run significantly faster than more generic code created at compile time.

Static Method

• Wrote before runtime (before compilation)

• public int DoSumLooping(int initialVal)• {• int result = 0;• for(int i = 1;i <=initialVal;i++)• {• result += i;• }• return result;• }

• Summation of N : 1+2+3+4+5+6+…..+N

Dynamic Method created at run time

• // Push zero onto the stack. For each 'i' • // less than 'theValue', • // push 'i' onto the stack as a constant• // add the two values at the top of the stack.• // The sum is left on the stack.

• generator.Emit(OpCodes.Ldc_I4, 0);• for (int i = 1; i <= theValue;i++)• {• generator.Emit(OpCodes.Ldc_I4, i);• generator.Emit(OpCodes.Add);• • }

Demo

• Programming_CSharp3

Problems

• Reflection APIs are known to cause problem on obfuscated assemblies.

Reference

• medialab.di.unipi.it/web/AP/Reflection.ppt

• Programming Microsoft .NET by Jeff Prosise

Questions

Thank you

Recommended