Use the C # reflection design to support scalable plug-ins

Source: Internet
Author: User
Tags ibase

 

1. Design Interface Class:

public interface IBase{     void Somefun();}

2. Design extension plug-ins:

class PluginCls:IBase{     public void Somefun()     {         Console.WriteLine("hello ,i am derived class");      }}

3. Main Program Design:

Class program {static void main (string [] ARGs) {Assembly ASM = assembly. loadFile (@".... \ plugincls. DLL "); Type [] clstypes = ASM. gettypes (); // you can access all types defined in the Assembly. // type [] clstypes = ASM. getexportedtypes (); // This method can only access the public-defined type foreach (Type E in clstypes) {If (E. isclass & typeof (IBASE ). isassignablefrom (E) // compatible with {ibase mth = (IBASE) activator. createinstance (E); // class instance to construct MTH. somefun (); // call the implementation method of the plug-in class} console. readkey ();}}

Program output:

 

In this way, the main application can load plug-ins designed by other people, without worrying about the new types defined by the plug-in, as long as the plug-in is designed according to the given interface principles,

The main program can be seamlessly loaded.

 

Reference: CLR via C #, Chapter 2

Jeffrey's implementation is too embarrassing. The book is a classic book, and his book is recommended for the split of walls!

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.