. NET Reflection (1)

Source: Internet
Author: User

. NET of Reflection

First edition

Content Summary
    • Objective
    • Reflection
    • View Meta data
    • Loading assemblies
    • Late binding
    • Method invocation
    • Use backgrounds for reflection, late binding, and custom attributes
    • Resources
Preface

The content of reflection, has always been hidden in the C # Advanced programming category in the voluminous books, C # primer AH C # proficient AH basic rarely mentioned, if the mention is ambiguous, it is difficult to fathom. This article is based on the practical purpose of "C # and. NET4 Advanced Programming (5th Edition)", part fourth, chapter 15th. NET reflection in the use of the analysis of the implementation of the reflection and simple application, does not involve the principle of performance issues discussed.

Before starting the reflection, the following needs to be understood in advance to read the 14th chapter of the book:
    • Name space
    • Assembly
    • Meta data
Outline of the 15th chapter Reflection

Reflection (Reflection) is the process of discovering a runtime type. Using the Reflection service, you can programmatically use a friendly object model to get meta-data information.

Reflection provides objects (type types) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and call its methods or access its fields and properties. If you use attributes in your code, you can use reflection to access them.

Reflection (C # and Visual Basic)MSDN

Using the. NET Framework when programming with reflection, you can use the System.Reflection namespace. This namespace provides classes that encapsulate many run-time concepts, such as assemblies, modules, types, methods, constructors, fields, and properties.

System.Reflection class
Language Components the corresponding. NET class
Assembly System.Reflection.Assembly
Module System.Reflection.Module
Abstract members System.Reflection.MemberInfo (all of the following base classes)
Type System.Type
Property System.Reflection.PropertyInfo
Field System.Reflection.FieldInfo
Event System.Reflection.EventInfo
Abstract methods System.Reflection.MethodBase (all of the following base classes)
Method System.Reflection.MethodInfo
constructor function System.Reflection.ConstructorInfo
Reflection hierarchy
    1. Loading assemblies (Assembly)
    2. Retrieving metadata (Type, PropertyInfo, FieldInfo, EventInfo, MethodInfo ...)
    3. Dynamic object creation/late binding (System.activator)
    4. Dynamic call method (Invoke)
View Meta Data

Metadata viewing for System.Type classes and System.Object.GetType() , Type.GetType() and typeof() methods

System.Object.GetType()Returns an instance of the type class that represents the current data object, as shown in the example, which GetType() needs to be called by an instance, so objects that cannot be instantiated, such as static classes, cannot be used GetType()

1 // only classes that can be instantiated are obtained 2 // a static class cannot be instantiated, so you cannot use this method to get 3 New DateTime (); 4 Type type = dt. GetType ();
Metadata  Type.GetType()  information can also be obtained using a fully qualified name based on the type, and in this way we do not need to provide compile-time information for that type, just a type string name.
Use the type full-name string class to get the type T = Type.GetType ("System.Int32");//To get static class metadata var Type = Type.GetType (" Consoleapplication1.staticclass ");

With typeof() the operator, we don't need to create an instance to extract the type information, but we still need to know the type's compile-time information, because the typeof() type's strongly typed name is required, not the text representation.

Use strongly typed names to get metadata information var type = typeof (DateTime);//staticclass is a custom static class type = typeof (Staticclass);

  

You can use either of these methods to obtain an instance of the type class, and then you can obtain the corresponding metadata information through a series of method classes provided by the type class, such as fields, properties, methods, etc.

Type class

Here GetMethods() 's an example of getting all the methods under the Int class, with the rest being roughly the same, no longer listing

            Type t = Type.GetType ("System.Int32");            foreach (Var method in T.getmethods ())            {                Console.WriteLine ("+" + method). Name);            }

  

Output

In addition, the type class provides some additional information such as:

    • IsAbstract: Whether abstract
    • IsPublic: Is public class
    • BaseType: base class Information
    • ......
More about Type class Poke: MSDN type class Loading Assemblies

There are scenarios where we need to load the assembly programmatically while the program is running, even if the assembly is referenced in the reference manifest, and this loading of external assemblies on demand is called dynamic loading

System.ReflectionDefines a class named assembly to use this class we can dynamically load an assembly and find properties about the assembly itself. With the assembly type, we can also dynamically load private or shared assemblies and be able to load assemblies from anywhere. Use the methods provided by the Assembly class Lode() LoadFrom() to do this.

LoadAnd LoadFrom There are numerous overloads, so you can use different methods depending on the scene, and return a assembly object.

 public static Assembly Load (AssemblyName assemblyref); public static Assembly Load (byte[] rawassembly); public static Assembly Load (String assemblystring); public static Assembly Load (AssemblyName assemblyref, Evidence assemblysecurity); public static Assembly Load (byte[] rawassembly, byte[] rawsymbolstore); public static Assembly Load (String assemblystring, Evidence assemblysecurity); public static Assembly Load (byte[] rawassembly, byte[] rawsymbolstore, Evidence securityevidence); public static Assembly Load (byte[] rawassembly, byte[] rawsymbolstore, Securitycontextsource securitycontextsource); public static Assembly LoadFile (string path); public static Assembly LoadFile (string path, Evidence securityevidence); public static Assembly LoadFrom (string assemblyfile); public static Assembly LoadFrom (String assemblyfile, Evidence securityevidence); public static Assembly LoadFrom (String assemblyfile, byte[] hashValue, AssemblyHashAlgorithm hashalgorithm); public static Assembly LoadFrom(String assemblyfile, Evidence securityevidence, byte[] hashValue, AssemblyHashAlgorithm hashalgorithm); 

  

Assembly.LoadMethod simply passes in a friendly name for an assembly that needs to be loaded into memory, so you need to copy the file you want to reflect into the current file bin (bin\debug) directory. Assembly.LoadFrommethod loads the specified file according to the absolute path of the file. You can also specify a network path, and if you specify a network path, the assembly is downloaded first and then loaded.

    This way you need to copy the file into the same directory under Bin/debug (Bin)    Assembly asm = assembly.load ("Microsoft.ApplicationBlocks.Data");    Console.WriteLine (ASM. FullName);    type[] types = asm. GetTypes ();    foreach (var item in types)    {        Console.WriteLine ("Type:{0}", item);    }

  

//DLL文件绝对路径 var assemblyFullPath = @"D:\Lab\Microsoft.ApplicationBlocks.Data.dll"; Assembly asm2 = Assembly.LoadFrom(assemblyFullPath); Console.WriteLine(asm2.FullName); foreach (var item in asm.GetTypes()) { Console.WriteLine("Type:{0}", item.Name); } 
late binding

We already know how to get the loading of an assembly and get the assembly's metadata, so how do we invoke a type method that is not added to the program's reference manifest at run time? The answer is late binding.

Late binding (late binding) is a technique that creates an instance of a given type and invokes its members at run time without needing to know at compile time that it exists. When you establish an application that is late bound to an external assembly type, the calling program manifest does not list the assembly because the assembly reference is not set.

System.ActivatorClass (defined in mscorlib.dll) is the key to late binding. We just need to focus on Activator.CreateInstance() the method, which is used to create an instance of a late binding type. CreateInstance()the same method also has multiple overloads, which can be used depending on the scenario.

        static void Latebinding ()        {            var assemblyfullpath = @ "D:\Lab\T.Entities.dll";            Try            {                var asm = Assembly.LoadFrom (assemblyfullpath);                var types = asm. GetTypes ();                var type = asm. GetType ("T.entities.customers");                Object obj = activator.createinstance (type);                Console.WriteLine ("Create a {0} using late Binding", obj);            }            catch (Exception)            {                throw;            }        }

  

method Invocation

We've loaded an assembly that doesn't have a reference, and we've created one of the members with a late binding , and the next thing to do is to use this instance for us, but first think about what we got in the previous instance is an object, Without a reference there is no way to convert to the corresponding object, then we cannot call its method!

To solve this problem, we still use the reflection to get the metadata information of the Location object instance, for example MethodInfo , by MethodInfo.Invoke implementing the method invocation.

    static void Invokenoparametermethod ()    {        var assemblyfullpath = @ "D:\Lab\T.Entities.dll";                Try        {            var asm = Assembly.LoadFrom (assemblyfullpath);            var type = asm. GetType ("T.entities.modelhelper");            Object obj = activator.createinstance (type);            Console.WriteLine ("Create a {0} using late Binding", obj);            "GetName" is a method in the Modelhelper class that returns a name for the string            MethodInfo mi = type. GetMethod ("GetName");                  Oil Invoke (obj, null);            String returnstr = mi. Invoke (obj, null) as String;            Console.WriteLine (RETURNSTR);        }        catch (MissingMethodException ex)        {            throw;        }    }

  

Use backgrounds for reflection, late binding, and custom attributes

The original book mentions a scene the product must be extensible by using third-party tools to extend the visual Studio IDE as an example of a possible way to solve this problem with third-party software providers:

    • First, the extensible application must provide some input means to allow the user to specify the module being inserted, which requires dynamic loading
    • Second, in order to insert into the environment, an extensible application must determine whether the module supports the correct functionality, which requires reflection
    • Finally, an extensible application must obtain a reference to the required infrastructure and invoke the member to trigger the underlying functionality, which often requires late binding

In addition, some of the situations I encountered

    • ORM frameworks are often used, for example, to automatically assign values to attributes
    • AddIn Pattern Development
    • Factory object is dynamically generated in abstract Factory mode
    • ......

In practice, not all scenarios require reflection, and there is a general view that reflection can affect performance, so it is not necessary to show that your technology is more bull than to involve a reflection. But as a technical means, understanding will think of the use, may be abused, and then will gradually understand its beauty, and finally for me to use.

References 14c#4.0 Essence (3rd edition)14c# and. NET 4 Advanced Programming (5th Edition)14c# Advanced Program (7th edition)

. NET Reflection (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.