Attributes, Reflection, and Dynamic Programming

Page 1

Attributes, Reflection, and Dynamic Programming

Learn More @ http://www.learnnowonline.com Copyright Š by Application Developers Training Company


Decorating Code With Attributes • Demo


Examples of Applications That Use Attributes • Attributes are meta-data you can add to code • Examples of applications: • The C# compiler • Web Services • Unit testing

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


C# Compiler Attribute Examples • ObsoleteAttribute marks code as being deprecated • ConditionalAttribute removes code when a pre-processing directive isn’t defined • DllImportAttribute enables calling Windows OS APIs


Creating New Attributes • Demo


Deriving From Attribute • Derive a new class from Attribute, a .NET Framework type • Give your class a suffix of “Attribute” • i.e. TestAttribute • Not required, but a common convention


Specifying Named and Positional Parameters • Positional parameters appear first • Named parameters follow • For: [DllImport("shell32.dll", EntryPoint="FindExecutable")]

• “shell32.dll” is positional • EntryPoint="FindExecutable" is named


Decorating with AttributeUsageAttribute • Three Parameters • AllowMultiple – can use attribute more than once • Inherited – applies to derived classes • ValidOn – defines where allowed to use


Using Reflection • Demo


Getting Type and TypeInfo • Reflection API split into two types • Type provides reference support • TypeInfo offers execution support


Exploring Type Members • Once you have a type, you can query its members: • GetFields • GetMethods • GetProperties • GetXxx

• Continue to explore as you need


Dynamic Invocation • You can dynamically invoke/run methods discovered through reflection • Get object reference, if instance • Specify parameters • Call Invoke(…) • Code runs


Coding Dynamic Types • Demo


Using Dynamic Types • • • • •

Declare type as dynamic Can call any member Can assign to any member No compile-time error Errors surface as runtime exceptions


The Expando Object • • • •

Lets you add/remove members dynamically Can pass object reference as parameter Use members dynamically too Get notified when add/remove occurs


Implementing DynamicObject • Derive from DynamicObject • Overrides let you do anything dynamically • Examples of methods you can override • TrySetMember • TryGetMember • TryInvokeMember


Questions? http://www.LearnNowOnline.com

Learn More @ http://www.learnnowonline.com Copyright Š by Application Developers Training Company


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.