Download presentation
Presentation is loading. Please wait.
Published byHollie Lindsay Mills Modified over 6 years ago
1
Reflection SoftUni Team Technical Trainers C# OOP Advanced
Software University
2
Table of Contents What? Why? Where? When? Reflection API Type Class
* Table of Contents What? Why? Where? When? Reflection API Type Class Reflecting Fields Reflecting Constructors Reflecting Methods (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
3
Questions sli.do #CSharp-OOP
4
Reflection What? Why? Where? When?
5
What is Metaprogramming?
Programming technique in which computer programs have the ability to treat other programs as their data Programs can be designed to: Read Generate Analyze Transform Modify itself while running.
6
What is Reflection? The ability of a programming language to be it’s own metalanguage Programs can examine information about itself
7
Why, Where Reflection? Code becomes more extendible
Reduces code length significantly Easier maintenance Testing Tools for programmers
8
When Reflection? If it is possible to perform an operation without using reflection, then it is preferable to avoid using it Cons from using Reflection Performance overhead Security restrictions Exposure of internals
9
Reflecting Class and Members
Reflection API Reflecting Class and Members
10
You need fully qualified class name as string
Type Class Primary way to access metadata Obtain at compile time if you know it’s name Obtain at run time if the name is unknown Type myType = typeof(ClassName); Type is the root of the System.Reflection functionality and is the primary way to access metadata. Use the members of Type to get information about a type declaration, about the members of a type (such as the constructors, methods, fields, properties, and events of a class), as well as the module and the assembly in which the class is deployed. Type describes data types. It stores type information in a variable, property or field. The Type class represents the program's metadata, which is a description of its structure but not the instructions that are executed. Type myType = Type.GetType("Namespace.ClassName") You need fully qualified class name as string © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
11
Class Name Obtain Class name
Fully qualified class name - Type.FullName Class name without the package name - Type.Name string fullName = typeOf(SomeClass).FullName; string simpleName = typeOf(SomeClass).Name; © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
12
Base Class and Interfaces
Obtain base class Obtain interfaces Only the interfaces specifically declared implemented by a given class are returned Type baseType = testClass.BaseType; Type[] interfaces = testClass.GetInterfaces(); © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
13
New Instance CreateInstance - creates an instance of a type by invoking the constructor that best matches the specified arguments Type sbType = Type.GetType("System.Text.StringBuilder"); StringBuilder sbInstance = (StringBuilder) Activator.CreateInstance(sbType); StringBuilder sbInstCapacity = (StringBuilder)Activator .CreateInstance(sbType, new object[] {10}); © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
14
Reflect Fields Obtain public fields Obtain all fields
FieldInfo field = type.GetField("name"); FieldInfo[] publicFields = type.GetFields(); FieldInfo[] allFields = type.GetFields( BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
15
Field Type and Name Get field name and type
FieldInfo field = type.GetField("fieldName"); string fieldName = field.Name; Type fieldType = field.FieldType; © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
16
Field Altering Type testType = typeof(Test); Test testInstance =
(Test) Activator.CreateInstance(testType); FieldInfo field = testType.GetField("testInt"); field.SetValue(testInstance, 5); int fieldValue = (int) field.GetValue(testInstance); WARNING: use with extreme caution as you could alter an objects internal state! © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
17
Access Modifiers Each modifier is a flag bit that is either set or cleared Check access modifier of a member of the class field.IsPrivate //private field.IsPublic //public field.IsNonPublic //everything but public field.IsFamily //protected field.IsAssembly //internal etc… IsPrivate – check if field is © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
18
Reflect Constructors Obtain constructors
Obtain all non static constructors ConstructorInfo[] publicCtors = type.GetConstructors(); ConstructorInfo[] allNonStaticCtors = type.GetConstructors( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
19
Reflect Constructors(2)
Obtain a certain constructor Get parameters type ConstructorInfo constructor = type.GetConstructor(new Type[] parametersType); Type[] parameterTypes = constructor.GetParameters(); © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
20
Instantiating Objects
Instantiating objects using constructor StringBuilder builder = (StringBuilder)constructor.Invoke(new object[] params); Supply an array of object parameters for each argument in the constructor you are invoking The .Invoke method takes an array of objects and you must supply exactly one parameter per argument in the constructor you are invoking. In this case it was a constructor taking a string, so one string must be supplied. © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
21
Reflect Methods Obtain public methods Obtain certain method
MethodInfo[] publicMethods = sbType.GetMethods(); MethodInfo appendMethod = sbType.GetMethod("Append"); MethodInfo overloadMethod = sbType.GetMethod( "Append", new []{typeof(string)}); © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
22
Method Invoke Obtain method parameters and return type Invoke methods
ParameterInfo[] appendParameters = appendMethod.GetParameters(); Type returnType = appendMethod.ReturnType; Parameters for the method appendMethod.Invoke( builder, new object[] { "hi!“ }); Target object instance © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
23
Live Exercises in Class (Lab)
Reflection Live Exercises in Class (Lab) © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
24
Summary What are the: Benefits Drawbacks Of using reflection?
Main benefit: code becomes easy to extend and maintain because it adapts at runtime Main drawback: - performance is sacrificed
25
Reflection https://softuni.bg/courses/
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
26
License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
27
Trainings @ Software University (SoftUni)
Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University Foundation softuni.org Software Facebook facebook.com/SoftwareUniversity Software University Forums forum.softuni.bg © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.