Download presentation
Presentation is loading. Please wait.
1
Reflection, Conversions, and Exceptions Tom Roeder CS215 2006fa
2
Remaining Constructs We’ve covered most of the core language At least as it differs from Java Need to see Reflection Exceptions Overloading/Operators Explicit and implicit casts and conversions
3
Reflection The ability to refer to the type system in code eg. Type t = Type.GetType(“int”); bool b = t.IsSubclassOf(typeof(object)); construct types from strings have classes that represent types Can explicitly compare types and determine subclassing (and other) relationships Useful for many applications
4
Reflection – Example We want to get a methods dynamically: C c = new C(); Type t = c.GetType(); for(int i = 0; i < 10; i++) { MethodInfo m = t.GetMethod(“m” + i); m.Invoke(c, null); } Type contains information about the type all nested types all methods, members, properties, etc whether or not it is an array
5
Reflection – is How do we get/check type information? use is operator: if (c is Guid) { … } returns true if it is this class If it is a subclass, is returns true reflects dynamic type information if compiler can decide statically, it will warn eg. int i = 0; if (i is object) { … } else { … } like instanceof in Java easy to abuse: can avoid proper inheritance
6
Reflection - as Instead of a cast, use as keyword returns a variable of the right type or null if not possible (no conversion exists) can only use for reference/interface types but can often convert to value types Better than trying to cast and throwing can be misused all the same may still need to cast if using a value type
7
Reflection – Attributes Assemblies contain metadata can be defined by programmer at compilation any class derived from System.Attribute naming convention _Attribute can be dropped and still understood using System; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class SimpleAttribute: Attribute {...}
8
Reflection – Attributes [Simple] class Class1 {...} [Simple] interface Interface1 {...} Multi-use or single-use attributes depends on AllowMultiple Positional and named parameters constructors define positional parameters non-static public RW fields define named
9
Reflection – Attributes Parameters limited in type numeric, string, and enum types object and System.Type single dimensional arrays of the above Uses authorship serializability help URLs any declarative information
10
Attribute Example Application Abstraction (see Singularity)Singularity add attributes that describe the application what resources used in OS what other applications it connects to use this information to build some components eg. access code for hardware resources add security information what does this application expect from extensions Used, eg for Device Drivers in Singularity
11
Attribute Example [DriverCategory] [Signature("/pci/03/00/5333/8811")] class S3TrioConfig: DriverCategoryDeclaration { // Hardware resources from PCI config [IoMemoryRange(0, Default = 0xf8000000, Length = 0x400000)] internal readonly IoMemoryRange frameBuffer; // Fixed hardware resources [IoFixedMemoryRange(Base = 0xb8000, Length = 0x8000)] internal readonly IoMemoryRange textBuffer;
12
Reflection – Attributes Conditional in System.Diagnostics takes a string representing a symbol calls to method are included only if the symbol is defined at the method call point Obsolete can return compiler errors or warnings useful for long-standing code
13
Reflection - Attributes PInvoke can import functions from native API [DllImport(“kernel”)] NtCreateFile(…) no guarantees about called code but allows direct access to OS and others We will discuss this more when we discuss unsafe mode
14
Reflection – Code Generation Can dynamically instantiate assemblies Reflection allows generation of MSIL eg. System.Reflection.Emit.MethodRental allows the replacement of a body with another can add before/after clauses Could write a program that generates another this is not good style but the power is occasionally useful
15
Conversions Implicit never fails to a “larger” type eg. int to long Explicit may fail to a “smaller” type eg. long to int User-defined conversions should be similar
16
Conversions Don’t make an implicit conversion that fails! or one across very different domains Implicit example: boxing conversion to an implemented interface User-defined conversions can define a conversion “operator” if not already defined and operates on our class
17
Conversions C# will only take one jump to convert eg. if have conversion S to X and X to T, will not convert S to T eg. public static implicit operator Hashtable(Example e) { Hashtable h = new Hashtable(); h[e.a.X] = e.a.X; return h; }
18
Operators Defines the meaning of an operator eg. +, -, *, /, % static method operates on two instances and returns a third unlike C++ where one instance is implicit one of the classes must be the defining class Can’t be part of an interface Can’t be overridden
19
Operator Examples public static C operator +(C first, C second) { C temp = new C(); temp.val = first.val + second.val; return temp; }
20
Operator Examples Suppose have class C that has a conversion to double and back. Is the following valid? C c1 = new C(); C c2 = new C(); C c3 = (C)((double)c1 + (double)c2); does it worry you? it should: why should + actually work like this? depends strongly on the conversion used what is the right way to do this?
21
Exceptions Inherit from System.Exception Control structure same as Java try-catch-finally can implement own exceptions Dynamic exceptions can occur at runtime eg. NullReference, OutOfBounds necessary to catch them
22
Exceptions Interesting cases: InnerExceptions any number of nested exceptions common interface to nesting Initializer catching exceptions implicitly then throws System.TypeInitializationException Exceptions in destructor try to execute base class otherwise discard exception
23
Checked and Unchecked Two contexts for evaluating arithmetic unchecked default context overflows do not throw exceptions can use unchecked operator to make explicit checked overflows throw System.OverflowException use checked operator
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.