All types in the CLR are self-describing – CLR provides a reader and writer for type definitions System.Reflection & System.Reflection.emit – You can ‘read’

Slides:



Advertisements
Similar presentations
Attributes Programming in C# Attributes CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Advertisements

The Type System1. 2.NET Type System The type system is the part of the CLR that defines all the types that programmers can use, and allows developers.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Advanced Object-Oriented Programming Features
Reflection Leveraging the Power of Metadata
.NET Attributes and Reflection “What a developer needs to know……” Dan Douglas Blog:
Reflection, Conversions, and Exceptions Tom Roeder CS fa.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Programming Languages and Paradigms Object-Oriented Programming.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
.NET Framework Introduction: Metadata
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 7 th & 8 th Lecture Pavel Ježek.
Java2C# Antonio Cisternino Part III. Outline Classes  Fields  Properties  virtual methods  new names  operator overloading Reflection  Custom attributes.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Advanced .NET Programming I 13th Lecture
The Metadata System1. 2 Introduction Metadata is data that describes data. Traditionally, metadata has been found in language- specific files (e.g. C/C++
.NET Framework & C#.
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
Kalpesh Padia Reflection in.Net. OVERVIEW 9/19/
Reflection in.Net Siun-Wai Seow. Objective Explain.NET Reflection When to use it? How to use it? Topic is in the final exam.
C# Programming Fundamentals of Object-Oriented Programming Fundamentals of Object-Oriented Programming Introducing Microsoft.NET Introducing Microsoft.NET.
Distributed Systems (236351) Tutorial 1 - Getting Started with Visual Studio C#.NET.
Programming Pillars Introduction to Object- Oriented Programming.
© FPT Software Advanced features in C# 1. © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda.
Reflection Leveraging the Power of Metadata. Objectives Provide an introduction to.NET Reflection Explain how applications can use Reflection to explore.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
ABHISHEK BISWAS.NET Reflection Dynamically Create, Find and Invoke Types.
.NET common type system. Role of type system provides a logically consistent and unchanging foundation ensures that programs can be checked for correctness.
Effective C# 50 Specific Way to Improve Your C# Item 42, 43.
E FFECTIVE C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner محمد حسین سلطانی.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programming in Java CSCI-2220 Object Oriented Programming.
1 Interfaces and Abstract Classes Chapter Objectives You will be able to: Write Interface definitions and class definitions that implement them.
Reflection.NET Support for Reflection. What is Reflection Reflection: the process by which a program can observe and modify its own structure and behavior.
Module 14: Attributes. Overview Overview of Attributes Defining Custom Attributes Retrieving Attribute Values.
Bill Campbell, UMB Microsoft's.NET C# and The Common Language Runtime.
Attributes C#.Net Software Development Version 1.0.
PerlNET: The Camel Talks.NET Jan Dubois The Perl Conference 6 San Diego, July 26 th 2002.
Introduction to Object-Oriented Programming Lesson 2.
Object Oriented Software Development 4. C# data types, objects and references.
.NET Mobile Application Development XML Web Services.
Bruno Cabral “Reflection, Code Generation and Instrumentation in the.NET platform” University of Coimbra.
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
Enum,Structure and Nullable Types Ashima Wadhwa. Enumerations, Enumerations, or enums, are used to group named constants similar to how they are used.
Delivering Excellence in Software Engineering ® EPAM Systems. All rights reserved. Reflection and Attributes.
.Net Reflection Taipan Tamsare. Overview Reflection core concepts Exploring metadata Detail information Attributes Building Types at runtime.
METADATA IN.NET Presented By Sukumar Manduva. INTRODUCTION  What is Metadata ? Metadata is a binary information which contains the complete description.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 7 th Lecture Pavel Ježek
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
Basic Introduction to C#
Creating Your Own Classes
Q Reflection Nauzad Kapadia MGB 2003
Module 5: Common Type System
15: Object Object Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Reflection SoftUni Team Technical Trainers C# OOP Advanced
Advanced .NET Programming I 7th Lecture
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
Programming Language Concepts (CIS 635)
CS360 Windows Programming
Chapter 3 The .NET Framework Class Library (FCL)
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Programming in C# CHAPTER 1
.NET and .NET Core 9. Towards Higher Order Pan Wuming 2017.
.NET and .NET Core 10. Enabling Contracts Pan Wuming 2017.
How to organize and document your classes
CIS 199 Final Review.
Quiz Points 1 Rules Raise your hand if you know the question
Jim Fawcett CSE775 – Distributed Objects Spring 2006
Advanced .NET Programming I 8th Lecture
Presentation transcript:

All types in the CLR are self-describing – CLR provides a reader and writer for type definitions System.Reflection & System.Reflection.emit – You can ‘read’ programs – You can map between type systems – You can interrogate objects and types inside a running program Reflection Overview

Execution model Cobol VB C++ C# CIL code (+ metadata) Loader/verifier Managed Code Uncompiled method call Execution Language compilers.NET languages JIT compiler

Reflection Core Concepts Metadata – Single location for type information and code – Code is literally contained within type information – Every.NET object can be queried for its type – Type metadata can be explored with Reflection Dynamic Type System – Highly dynamic and language independent – Types may be extended and built at run time Allows on-the-fly creation of assemblies See my CodeDom tutorial

Metadata uses Allows type developed in a PL to be used by code in other PL GC uses to traverse objects Serialization (essential for Web Services) IDE (e.g. IntelliSense)

Exploring Metadata Who are you? What are you? Anything special about you? Now tell me what you have! Types and Instances

System.Type Access to meta-data for any.NET type Returned by System.Object.GetType() Allows drilling down into all facets of a type – Category: Simple, Enum, Struct or Class – Methods and Constructors, Parameters and Return – Fields and Properties, Arguments and Attributes – Events, Delegates and Namespaces C# also has the, typeof(), is and as operators.

What are you? Value, Interface or Class? – IsValueType, IsInterface, IsClass Public, Private or Sealed ? – IsNotPublic, IsSealed Abstract or Implementation? – IsAbstract Covers all possible properties of a managed type Very intuitive API, no "Parameter Hell"

Type Reflection Object IEnquire IPrint ITransfer Account Savings Savings.BaseType ==Account Savings.BaseType.BaseType == Object ITransfer.BaseType == null Account.IsSubClassof(IEnquire) == false Savings.IsSubClassof(Account) == true Savings.GetInterfaces() == { IPrint, ITransfer, IEnquire } IEnquire.IsAssignableFrom(Savings) == true

Reflection and the CLR type system System.Object EventInfoPropertyInfoFieldInfoMethodBase System.Type ParameterInfoMemberInfoModuleAssembly MethodInfoConstructorInfo

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

Reflection MetaData Samples // Test sample class public class Test { private int n; public Test(int a) { n=a;} public void Foo(float a, object b, string c) { } } //Retrieve the Type object public static int Main(string[] args) { Type type1 = typeof (Test); Test t1 = new Test(0); Type type2 = t1. GetType (); Console.WriteLine(“type of t1 is {0}”, type2); return 0 } Note: type1==type2 ReferenceEquals(type1, type2) == true

Reflection Type and Instances Type Safety First! Type checking at run time – if (o is Customer) { … } Dynamic Invocation through Reflection – Support for late binding: MethodInfo.Invoke() MethodInfo.Invoke FieldInfo.SetValue() FieldInfo

Reflection GetMethods Example //Get a list of methods supported by a class public static int Main(string[] args) { Type type1 = typeof(Test); MethodInfo[] minf = type1.GetMethods();GetMethods foreach (MethodInfo m in minf) { //Print out the method name and whether it is public Console.WriteLine(“Name: “+ m.Name + “,” + ((m.IsPublic) ? “ public” : “”) + ((m.IsVirtual) ? “virtual” : “”); //Get the list of parameters ParameterInfo[] pi = m.GetParameters(); foreach (ParameterInfo p in pi) Console.WriteLine(“ “ + p.ParameterType + “ “ + p.Name); } return 0 } Name: Foo, public System.Single a System.Object b System.String c Name: GetType, public Name: ToString, public virtual Name: Equals, public virtual System.Object obj Name: GetHashCode, public virtual Press any key to continue...

Reflection 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

Anything special about you? Special Memory Layout? – IsAutoLayout – IsExplicitLayout – IsLayoutSequential COM Objects? – IsCOMObject More… – IsUnicodeClass – IsSpecialName, etc.

Now tell me what you have! Finding and Exploring Members – MemberInfo: GetMembers(), FindMembers() Exploring Fields and Properties – FieldInfo: GetFields(), PropertyInfo: GetProperties() Exploring Constructors, Methods and Events – GetConstructors(), GetMethods(), GetEvents() Exploring attributes, determining implemented interfaces, enumerating nested types, … Summary: Everything you may ever want to know

Type and Instances Type Safety First! Type checking at runtime – C#: if (o is Customer) { … } – VB: If TypeOf o Is Customer Then … End If Dynamic Invocation through Reflection – Support for late binding MethodInfo.Invoke() FieldInfo.SetValue() PropertyInfo.SetValue()

Reflection Dynamic Creation Example You can use CreateInstance and other methods to create instances at run-time and call their methods and properties. See the example here for more info.here –

Reflection The Bigger Picture Types know their module; modules know their types Modules know their assembly and vice versa Code can browse and search its entire context Assembly Module Class Struct Constructor Method Field Class Interface Class Delegate Class Interface

Traverse every element in an assembly Using System.Reflection; public static void WalkAssembly(String assemblyName) { Assembly assembly = Assembly.Load (assemblyName); foreach (Module module in assembly.GetModules()) foreach (Type type in module.GetTypes()) foreach (MemberInfo member in type.GetMembers()) Console.WriteLine ( “ {0}.{1} ”, type, member.Name; }

Object Creation OK, now see my CodeDom tutorial

Serialization Save state of an object on disk or send to a stream (we will cover this more later): public class Point : { public double x; public double y; public double length; // computed from x, y };

Solutions Inherit from a base type: class Point : Serializable { … } but … – base type does not know derived type – requires multiple inheritance Java solution: class Point implements Serializable { … } but … – method granularity – customization requires full rewrite of WriteObject, ReadObject

Solution: Attributes [Serializable] public class Point : { public double x; public double y; [NonSerialized] public double length; // computed from x, y };

Reflection Summary Reflection = System.Type + GetType() Explore type information at runtime Enables attribute-driven programming Bottom line: Fully self-contained structural model Used extensively in Visual Studio

VisualStudio.NET and Reflection Component Class Description DefaultValue Help Localizable ReadOnly ComponentMode l Attributes Toolbox Properties Window Designers Help

System.AddIn There is a new set of classes in the System.AddIn namespace for aiding in plug-in architectures. I have not had a chance to look at this closely, but it appears to be more for creating Adapter’s (see the Adapter design pattern) and creating a common interface (called an IContract). In other words allowing a plug-in that did not support your interface in the first place. See AddIns-with-System-AddIn.aspx. AddIns-with-System-AddIn.aspx