C # Reflection and Reflection interface

Source: Internet
Author: User

The reflection is described in the previous article, the following is mainly about the actual use of some reflection.

By reflecting us, I can get the interface and also get the class that implements the interface, at which point the interface reference can access an instance of the implementation class.

I first defined an interface:

     Public Interface IPerson    {         void SetName (string  name);          void SayHello ();         }

To define a class implementation:

namespacepeople{ Public classPeople:iperson { Public stringName {Set; Get; }         Public stringSex {Set; Get; }         Public stringAge {Set; Get; }         Publicpeople () {} PublicPeople (stringname) {Name=name; }         Public voidSetName (stringname) {Name=name; }         Public voidSayHello () {Console.WriteLine ("Hello everyone, I am:"+Name); }    }}

Implemented by reflection:

namespaceconsoleapp1{classProgram {Static voidMain (string[] args) {IPerson IPerson=NULL; Assembly Assembly= Assembly.Load ("people"); Type[] Types=Assembly.            GetTypes (); foreach(varTinchtypes) {                if(T.getinterface ("IPerson") !=NULL) {IPerson=(IPerson) activator.createinstance (t); }            }            if(IPerson! =NULL) {IPerson. SetName ("Vidyut 厶"); IPerson.            SayHello ();        } console.readline (); }    }}

C # Reflection and Reflection interface

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.