[C # advanced series] 23 assembly loading and reflection,

Source: Internet
Author: User
Tags mscorlib

[C # advanced series] 23 assembly loading and reflection,

Assembly Loading

Assembly Loading. CLR uses the System. Reflection. Assembly. Load Static Method. Of course, we can also explicitly call this method.

There is also an Assembly. LoadFrom method that loads the Assembly with the specified path name. In fact, it first obtains the AssemblyName object through AssemblyName. GetAssemblyName, and then calls the Assembly. Load Method.

In this case, the load method searches for the Assembly in each location (as described in Chapter 03). If the Assembly has been loaded, the loaded assembly is returned. If the Assembly is not loaded, the loaded assembly is loaded, if not, load the Assembly given by the path. (It is clear that the specified Assembly may not be loaded, but may be another one. Here, if the version number is updated every time a strong-naming assembly is generated, the behavior of the LoadFrom method will conform to expectations)

The LoadFrom method allows passing a Url as a real parameter. CLR will download the file, install it in the user's download cache, and then load the file from there.

The ReflectionOnlyLoadFrom function can also load the Assembly and prohibit any code execution in the Assembly.

Build dynamic and scalable applications using reflection

Since the Assembly is loaded, there should be a way to use classes defined in the Assembly. This method is reflection.

Using the types contained in the System. Reflection namespace, you can write code to reflect the metadata table and provide an object model for the metadata contained in the loaded assembly.

Reflection examples:

First, create an assembly for reflection. The Code is as follows:

namespace HelloWorld{    public class Man    {        public string _name;        public Man(String name) {            this._name = name;        }        public void ShowName() {            Console.WriteLine(this._name);        }    }}namespace HelloWorld{    public class Troy:Man    {        private string _jobName;         public Troy(string name,string jobName):base(name) {            this._jobName = jobName;        }        public void ShowJobName() {            Console.WriteLine(this._jobName);        }     }}

Then a file named HelloWorld. dll is generated, and reflection is started.

// First load the Assembly and obtain the Assembly object Assembly myAssembly = Assembly. loadFrom ("D: \ HelloWorld. dll "); // The Public Type foreach (type Type in myAssembly. exportedTypes) {// print the full name of the type Console. writeLine ("type Full name:" + type. fullName); Console. writeLine (type. base class of FullName + ":" + type. baseType. fullName); // determine whether the type is String (of course this is impossible, because only Man and Troy) if (type = typeof (String) {Console. writeLine ("there is a String Type");} // Type object is lightweight Type reference, more comprehensive information in the TypeInfo (Retrieve TypeInfo object will force CLR to ensure that the type of definition assembly has been loaded, so as to parse the type. (Expensive), // convert TypeInfo typeInfo = IntrospectionExtensions as follows. getTypeInfo (type); // You can also convert it to Type tmpType = typeInfo. asType (); // generic Type openType = typeof (Dictionary <,>); // Open Type closedType = openType. makeGenericType (typeof (int), type); // closed type // instantiate Object obj = Activator. createInstance (closedType); Console. writeLine (obj. getType ());}

Reflection Performance

Reflection is a powerful mechanism, but it also has its disadvantages:

  • Reflection does not guarantee type security during compilation, because it only relies on strings to instantiate classes and perform other operations at runtime.
  • The reflection speed is very slow, because members are identified by strings at runtime, and they are found and used. String is used for search throughout the process.

Design applications supporting add-on

When building extensible applications, interfaces are generally used instead of base classes, because interfaces allow add-on developers to select their own base classes.

When defining parameters and returning classes for methods of the host interface class, try to use interfaces and types defined by MSCorLib. dll. Because CLR only loads one MSCorLib. dl, there is no type version mismatch, and it helps reduce the memory requirements of applications.

Reflection and type members

System. Reflection. MemberInfo encapsulates a set of attributes common to all types of members. Some of its derived classes, such as MethodInfo, encapsulate more attributes related to members of specific types.

The code is easy to understand:

class Program    {        static void Main(string[] args)        {            Type type = typeof(Troy);            Object obj = Activator.CreateInstance(type);            MethodInfo[] arrMethod= type.GetMethods();            foreach (var methodInfo in arrMethod) {                if (methodInfo.GetParameters().Length == 0)                {                    methodInfo.Invoke(obj, null);                }            }            Console.Read();        }    }    public class Troy{        public string name;        public Troy() {            name = "Troy";        }        public void Show() {            Console.WriteLine(name);        }    }

For FieldInfo (field) and PropertyInfo (attribute), you can use GetValue and SetValue to obtain and set instance values,

You can use Invoke to call MethodInfo and ConstructorInfo,

For EventInfo (events), you can use AddEventHandler and RemoveHandler to increase the Event Callback Function and reduce the callback function.

The above method is actually very troublesome. If you use the dynamic method, it will be as simple as writing a program in general.

 

Related Article

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.