Advanced .NET Programming I 7th Lecture

Slides:



Advertisements
Similar presentations
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Advertisements

Java Virtual Machine (JVM). Lecture Objectives Learn about the Java Virtual Machine (JVM) Understand the functionalities of the class loader subsystem.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
C# Structs, operator overloading & attributes. Structs ~ Structures Structs are similar to classes: they represent data structures with data and functions.
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++
Writing Object Oriented Software with C#. C# and OOP C# is designed for the.NET Framework  The.NET Framework is Object Oriented In C#  Your access to.
.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.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 7 th & 8 th Lecture Pavel Ježek.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Advanced .NET Programming I 13th Lecture
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.
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’
© 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.
Effective C# 50 Specific Way to Improve Your C# Item 42, 43.
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.
C# part II Delegates and Events Delegates and Events Dynamic functions Dynamic functions Extension methods Extension methods Closures Closures.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
Attributes C#.Net Software Development Version 1.0.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 8 th Lecture Pavel Ježek
Reflection Bibliografie: Sun: The Java Tutorials – The Reflection API IBM developerWorks:
Wel come To Seminar On C#.
Bruno Cabral “Reflection, Code Generation and Instrumentation in the.NET platform” University of Coimbra.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 4 th Lecture Pavel Ježek
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Overview CNS 3260 C#.NET Software Development. 2.NET Framework Began in 2000 Developed in three years (2000 to 2003) Operating System Hardware.NET Framework.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 7 th Lecture Pavel Ježek
.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.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 7 th Lecture Pavel Ježek
C# for C++ Programmers 1.
NESTED CLASSES REFLECTION PROXIES.
Advanced .NET Programming II 6th Lecture
15: Object Object Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Methods Attributes Method Modifiers ‘static’
Advanced .NET Programming I 8th Lecture
CSE 413, Autumn 2002 Programming Languages
Advanced .NET Programming I 4th Lecture
Reflection SoftUni Team Technical Trainers C# OOP Advanced
Reflection SoftUni Team Technical Trainers C# OOP Advanced
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
Indexer AKEEL AHMED.
CS360 Windows Programming
5.1 Being Objects and A Glimpse into Coding
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Chapter 9 Inheritance and Polymorphism
.NET and .NET Core 9. Towards Higher Order Pan Wuming 2017.
.NET and .NET Core 10. Enabling Contracts Pan Wuming 2017.
CIS 199 Final Review.
What is Reflection? Some Definitions….
What is Reflection? Some Definitions….
Advanced .NET Programming I 9th Lecture
Advanced .NET Programming I 8th Lecture
Advanced .NET Programming I 5th Lecture
C# Language & .NET Platform 10th Lecture
- This slide is intentionally left blank -
Advanced .NET Programming I 4th Lecture
C# Language & .NET Platform 11th Lecture
Advanced .NET Programming I 6th Lecture
C# Language & .NET Platform 3rd Lecture
C# Language & .NET Platform 9th Lecture
C# Language & .NET Platform 4th Lecture
C# Language & .NET Platform 12th Lecture
Presentation transcript:

Advanced .NET Programming I 7th Lecture Pavel Ježek pavel.jezek@d3s.mff.cuni.cz Some of the slides are based on University of Linz .NET presentations. © University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License (http://www.msdnaa.net/curriculum/license_curriculum.aspx)

Reflection Permits access to meta-information of types at run-time System.Reflection allows: Getting meta-information about assemblies, modules and types Getting meta-information about the members of a type Dynamic creation of instances of a type at run-time Search for methods and their dynamic invocation at run-time Accessing values of properties and fields of an object Design of new types at run time - namespace System.Reflection.Emit

Reflection Class Hierarchy Assembly GetTypes() Type * BaseType * Interfaces GetFields() * FieldInfo MemberInfo GetMethods() * MethodInfo MethodBase GetConstructors() * ConstructorInfo GetProperties() * PropertyInfo GetEvents() * EventInfo

Class Type Type used for meta-description of all types in the run-time system Provides access to the meta-information about its members public abstract class Type : MemberInfo, IReflect { public abstract string FullName {get;}; public abstract Type BaseType {get;}; public Type[] GetInterfaces(); public bool IsAbstract {get;}; public bool IsClass {get;}; public bool IsPublic {get;}; … public ConstructorInfo[] GetConstructors(); public virtual EventInfo[] GetEvents(); public FieldInfo[] GetFields(); public MethodInfo[] GetMethods(); public PropertyInfo[] GetProperties(); ... Type name Direct base type List of implemented interfaces Properties of type Getting constructors, events, fields, methods, properties Optionally parameterized by BindingFlags

Example: Handling plug-ins “Plug-in” is any class implementing IMyPlugin interface string[] files = Directory.GetFiles(path, "*.dll"); // returns full paths foreach (string f in files) { Assembly a = Assembly.LoadFile(f); Type[] types = a.GetTypes(); foreach (Type t in types) { if (t.IsClass) { if (t.GetInterface(“IMyPlugin”) != null) { IMyPlugin p = (IMyPlugin) Activator.CreateInstance(t); // add p to list of all installed plug-ins }

Attributes with Parameters name parameters come after pos. parameters positional parameter Example [Obsolete("Use class C1 instead", IsError=true)] // causes compiler message saying public class C {...} // that C is obsolete Positional parameter = parameter of the attribute's constructor Name parameter = a property of the attribute Attributes are declared as classes public class ObsoleteAttribute : Attribute { // class name ends with "Attribute" public string Message { get; } // but can be used as "Obsolete" public bool IsError { get; set; } public ObsoleteAttribute() {...} public ObsoleteAttribute(string msg) {...} public ObsoleteAttribute(string msg, bool error) {...} } values must be constants Valid variants: [Obsolete] // Message == "", IsError == false [Obsolete("some Message")] // IsError == false [Obsolete("some Message", false)] [Obsolete("some Message", IsError=false)]

AttributeUsage AttributeUsage describes how user-defined attributes are to be used public class AttributeUsageAttribute : Attribute { public AttributeUsageAttribute (AttributeTargets validOn) {...} public bool AllowMultiple { get; set; } // default: false public bool Inherited { get; set; } // default: false } Usage [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple=false)] public class MyAttribute : Attribute { ... }

Defining Your Own Attributes Declaration [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited=true)] class CommentAttribute : Attribute { string text, author; public string Text { get {return text;} } public string Author { get {return author;} set {author = value;} } public Comment (string text) { this.text = text; author ="HM"; } } Usage [Comment("This is a demo class for Attributes", Author="XX")] class C { ... } Querying the attribute at runtime class Attributes { static void Main() { Type t = typeof(C); object[] a = t.GetCustomAttributes(typeof(CommentAttribute), true); foreach (CommentAttribute ca in a) { Console.WriteLine(ca.Text + ", " + ca.Author); }

Reflection Example Print all existing types in a given assembly Type[] types = a.GetTypes(); foreach (Type t in types) Console.WriteLine(t.FullName); Print all existing methods of a given type Type hw = a.GetType("Hello.HelloWorld"); MethodInfo[] methods = hw.GetMethods(); foreach (MethodInfo m in methods) Console.WriteLine(m.Name); Hello.HelloWorld GetType ToString Equals GetHashCode

Reflection Example Create a new instance of a given type Assembly a = Assembly.Load("HelloWorld"); object o = a.CreateInstance("Hello.HelloWorld"); Get method ToString(), which has no parameters Invoke the method Type hw = a.GetType("Hello.HelloWorld"); MethodInfo mi = hw.GetMethod("ToString"); object retVal = mi.Invoke(o, null);

Reflection: Accessing Private Fields using System.Reflection; class HelperClass { private int privateData; public int PublicData { get { return privateData; } set { privateData = value; } } class Program { static void Main(string[] args) { HelperClass hc = new HelperClass(); hc.PublicData = 123; Type type = hc.GetType(); FieldInfo fi = type.GetField("privateData", BindingFlags.Instance | BindingFlags.NonPublic); Console.WriteLine(fi.GetValue(hc)); fi.SetValue(hc, 456); Console.WriteLine(hc.PublicData);

Reflection: Accessing Private Fields using System.Reflection; class HelperClass { private int privateData; public int PublicData { get { return privateData; } set { privateData = value; } } class Program { static void Main(string[] args) { HelperClass hc = new HelperClass(); hc.PublicData = 123; Type type = hc.GetType(); FieldInfo fi = type.GetField("privateData", BindingFlags.Instance | BindingFlags.NonPublic); Console.WriteLine(fi.GetValue(hc)); fi.SetValue(hc, 456); Console.WriteLine(hc.PublicData); WARNING: SLOW & DANGEROUS!!!

MEF

Lambda Expressions as Delegates When assigned to a delegate, equivalent code of an anonymous method is generated at compile time! value => (value + 2) * 10 Func<int, int> f = Compile time generation IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: add IL_0003: ldc.i4.s 10 IL_0005: mul IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret

Lambda Expressions as Expression Trees Permit lambda expressions to be represented as data structures instead of executable code Lambda expression convertible to delegate D (assignment causes code generation) is also convertible to expression tree (abstract syntax tree) of type System.Linq.Expressions.Expression<D> (assignment causes expression tree generation – compile time generation of code, that creates the expression tree [class instances] at runtime) Expression trees are immutable value => (value + 2) * 10 Func<int, int> f = Expression<Func<int, int>> e = Compile time generation Compile time generation IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: add IL_0003: ldc.i4.s 10 IL_0005: mul IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret new LambdaExpression( new BinaryExpression( ParameterExpression(“value”) ConstantExpression(2) ) ConstantExpression(10)

Expression Trees Classes inheriting from Expression (since .NET 3.5): System.Linq.Expressions.BinaryExpression System.Linq.Expressions.ConditionalExpression System.Linq.Expressions.ConstantExpression System.Linq.Expressions.InvocationExpression System.Linq.Expressions.LambdaExpression System.Linq.Expressions.MemberExpression System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.NewExpression System.Linq.Expressions.NewArrayExpression System.Linq.Expressions.MemberInitExpression System.Linq.Expressions.ListInitExpression System.Linq.Expressions.ParameterExpression System.Linq.Expressions.TypeBinaryExpression System.Linq.Expressions.UnaryExpression New classes inheriting from Expression (since .NET 4.0): System.Linq.Expressions.BlockExpression System.Linq.Expressions.LoopExpression System.Linq.Expressions.TryExpression …

Expression Trees and LINQ

Lambda Expressions as Expression Trees value => (value + 2) * 10 Func<int, int> f = Expression<Func<int, int>> e = Compile time generation Compile time generation IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: add IL_0003: ldc.i4.s 10 IL_0005: mul IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret new LambdaExpression( new BinaryExpression( ParameterExpression(“value”) ConstantExpression(2) ) ConstantExpression(10) Runtime time generation by JIT machine code (e.g. x86) (code actually executed by real CPU)

Expression Trees to Dynamic Methods (via Implicit Reflection.Emit) Runtime generation of CIL code of a dynamic method from expression tree instance: value => (value + 2) * 10 Func<int, int> f = Expression<Func<int, int>> e = Compile time generation Compile time generation IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: add IL_0003: ldc.i4.s 10 IL_0005: mul IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret new LambdaExpression( new BinaryExpression( ParameterExpression(“value”) ConstantExpression(2) ) ConstantExpression(10) Runtime time generation f = e.Compile(); Runtime time generation by JIT machine code (e.g. x86) (code actually executed by real CPU)