Assembly loading and Reflection (ii): actual combat

Source: Internet
Author: User

Directory:

    • Previous article: http://www.cnblogs.com/sunchong/p/4550476.html
    • Demo

First, the Demo

The following demo uses a strategy model to mimic the plugin mechanism. Let's give an example of sending an email:

1, a Policy class library: strategy, which defines the interface that the message needs to implement: Iemailstrategy.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacestrategy{ Public InterfaceIemailstrategy {stringfrom {Get; } stringto {Get; }        stringSubject {Get; } BOOLSend (string  from,stringTo,stringsubject); }}

2, a specific implementation of the class library: target, the specific mailbox delivery policy implementation: Tow_email.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingstrategy;namespacetarget_1{ Public classEmail:iemailstrategy { Public stringTestfield_1 =string.        Empty;  Public intTestfield_2 =0;  PublicEmail (string  from,stringTo,stringsubject) {_from= from; _to=to ; _subject=subject; }        Private ReadOnly string_from; Private ReadOnly string_to; Private ReadOnly string_subject;  Public stringFrom {Get{return_from;} }         Public stringTo {Get{return_to;} }         Public stringSubject {Get{return_subject;} }         Public BOOLSend (string  from,stringTo,stringsubject) {Console.WriteLine ("Send Email successed!"); return true; }    }}

3, finally my host program, Reflectiontest, the specific mailbox policy implementation Target_1.dll (can be regarded as a third-party code) DLL copy to, the host program related directory.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacereflectiontest{classProgram {Static voidMain (string[] args) {            //gets the path of the current main program            stringHostfilepath =System.IO.Path.GetDirectoryName (System.Reflection.Assembly.GetEntryAssembly ().            Location); //Get DLL Path            string[] dlls = System.IO.Directory.GetFiles (Hostfilepath,"*.dll"); foreach(stringDllinchDLLs) {                //Load DLLSystem.Reflection.Assembly Assembly =System.Reflection.Assembly.LoadFrom (DLL); if(Assembly! =NULL&& Assembly. GetName (). Name = ="target_1") {Console.WriteLine ("Assembly name:{0}", assembly.                    FullName); //get all public classes in an assemblytype[] Types =Assembly.                    Getexportedtypes (); foreach(Type tinchtypes) {Console.WriteLine ("Type name: {0}", T.fullname); if(T.isclass &&typeof(Strategy.iemailstrategy). IsAssignableFrom (t)) {//gets the public member of the current classSystem.reflection.memberinfo[] Members =t.getmembers (); string  from="[email protected]"; stringto ="[email protected]"; stringSubject ="Come on Baby"; Console.WriteLine ("----instantiation----"); Strategy.iemailstrategy Email= (strategy.iemailstrategy) System.Activator.CreateInstance (T, from, to, subject); if(Email! =NULL)                            {                                string_f=email.                                from; string_t=email.                                to; string_s=email.                                Subject; Email.                                                           Send (_f,_t,_s); }                                                                                                                 //FieldConsole.WriteLine ("----Field----"); System.reflection.fieldinfo[] Fields=T.getfields (); foreach(varFinchFields ) {Console.WriteLine ("Field name: {0}", F.name); Console.WriteLine ("Field type: {0}", f.fieldtype.tostring ()); Console.WriteLine ("Field value: {0}", F.getvalue (email).                                                                                            ToString ()); }                                                        //PropertiesConsole.WriteLine ("----Property----"); System.reflection.propertyinfo[] Ppinfo=t.getproperties (); foreach(varPinchppinfo) {Console.WriteLine ("PropertyInfo name: {0}", p.name); Console.WriteLine ("PropertyInfo can read: {0}", p.canread.tostring ()); Console.WriteLine ("PropertyInfo can write: {0}", p.canwrite.tostring ()); Console.WriteLine ("PropertyInfo value: {0}", P.getvalue (email)); }                            //MethodConsole.WriteLine ("----Method----"); System.reflection.methodinfo[] Methodsinfo=T.getmethods (); foreach(varMtinchmethodsinfo) {Console.WriteLine ("MemberInfo name: {0}", Mt.                                Name); Object[] objs=New Object[]{"[email protected]","[email protected]","Come on baby!"}; if(Mt. name=="Send") Mt.                                Invoke (EMAIL,OBJS); //All-in-all method: Here's how it's doneT.invokemember ("Send", System.Reflection.BindingFlags.InvokeMethod,NULL, email, OBJS);                        } console.readkey (); }                    }                }            }        }    }}

Summarize:

1. Conventional reflection

Load assembly---> Filter class getexportedtypes ()---> Instantiate (System.Activator.CreateInstance)---> Get class Public member GetMembers ()--- ; Type class: GetFields (), GetProperties (), GetMethods ()

2, All-round reflection: InvokeMember ("Send", System.Reflection.BindingFlags.InvokeMethod, NULL, email, OBJS);

Assembly loading and Reflection (ii): actual combat

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.