C # Reflection

Source: Internet
Author: User

The concept of Reflection: Reflection provides objects (type types) that encapsulate 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.

General use: Factory class, to create an instance of a class through reflection, to achieve decoupling between layers: Data layer → data Session layer → business logic layer. Where the data session layer creates an instance of the data layer through reflection, called by the business logic layer.

function in Reflection type
//determine if there is an inheritance relationship between two members-the latter inherits from the formerBOOLb=typeof(person). IsAssignableFrom (typeof(Student));//student inherits the person//determines whether the current class is an instance of an objectStudent st =NewStudent (); Person P=NewPerson ();BOOLs =typeof(person). IsInstanceOfType (ST);//student inherits the person result to trueBOOLb = P.gettype (). IsInstanceOfType (ST);//The result is true GetType an instance of the current object//determine if a class is a subclass of another class--subclass put firstBOOLC=typeof(person). IsSubclassOf (typeof(Student)); //to determine whether a class is an abstract classtypeof(Class). IsAbstract

Use of common classes in reflection

Requirements: Get the members of the common assembly through reflection and use the Members

1. Put Common.dll into the Bin/debug directory of the application

string Path = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,"Common.dll"  assembly.loadfile(path);  // Absolute Path  required LoadFile Load Path assembly contents        --also not necessarily in the debug directory, you can build an absolute path or type[] tp = the. GetTypes ();             // get all Types    in an assembly Getexportedtypes (); Get public type

2. You can traverse a type in an assembly to get the namespace and type name of the type

foreach inch TP) {     Console.WriteLine (item. Name);              // type name  -the name of the class or interface under Common    Console.WriteLine (item. Namespace);        // name Space
}

3. Create a Type Object

A: Create an object without constructors

Object o=  . CreateInstance ("common.filecommon");     // Filecommom is a class → namespace for the common namespace. Class name   

B: The reflected type has a constructor

Type type =. GetType ("common.filecommon");    // gets the type object of the specified name Object " Parameters ");

Note: If the reflected type has a constructor, use the above code in the case of the. CreateInstance An error occurs, and if there is a constructor, how do you know the arguments to the constructor function?

ConstructorInfo [] info= type. GetConstructors ();    // querying all constructors, you can see the argument types that the constructor needs to pass parameters

4. Get all the attributes in the data type

PropertyInfo  [] pinfo   = type. GetProperties ();   // gets the property  and can then traverse

5. Get all the functions in the data type

MethodInfo [] minfo =type. GetMethods ();   // get all the functions

6. Purpose: Call function

MethodInfo method= type. GetMethod ("writedata");    // The WriteData method in this class " parameters of the WriteData method ");     // o The Type object created above

synthesis: when you get a. dll assembly, you need to get all the types, that is, the class in the assembly, and then, depending on the name of the class you want, create the object of the specified name, such as type type =.  GetType ("Common.filecommon"); And then takes the type to get the constructor, all functions, attributes (and some can get the type. Method name to obtain the appropriate requirements). Then choose the method that creates the type object (constructed or not constructed). It is then called according to the obtained function, passing in the corresponding parameter.

Example 1: The factory class creates an instance of the class through reflection:

Step ①: in Web. config (Web. config, program is app. config), configure the file configuration:

<appsettings><add key="assemblypath" value="Xsh.OA.DAL  " />   // path <add key="NameSpace" value= " Xsh.OA.DAL " />     // namespace </appSettings>

Step ②: Get the information you just configured

 Public Static ReadOnly string AssemblyPath = configurationmanager.appsettings["assemblypath"];  Public Static ReadOnly string NameSpace = configurationmanager.appsettings["NameSpace"];

Step ③: Create an instance of the class:

  Public StaticIuserinfodal Createuserinfodal () {stringFullClassName = NameSpace +". Userinfodal"; returnCreateInstance (FullClassName) asIuserinfodal;//Iuserinfodal the interface inherited for Userinfodal.  }  Private Static ObjectCreateInstance (stringclassName) {            varassembly=Assembly.Load (assemblypath); returnAssembly.  CreateInstance (ClassName); }//at this point, when you call Createuserinfodal this method, you create an instance of Userinfodal and then point out the method based on that instance .

Example 2: Making a shutdown plug-in using reflection

Features: If additional plugins are needed, add the. dll file under the path, delete the plugin and delete the appropriate. dll file

            //Get file path            stringPath = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,"Plug");//bin/debug/plug storing. dll files            string[] files =directory.getfiles (path); foreach(stringIteminchfiles) {Assembly=assembly.loadfile (item); Type [] Types=The .                Getexportedtypes ();  for(inti =0; I < types. Length; i++)                {                    //determines whether the class is in an interface, and is not an abstract class                    if(typeof(IPlugin). IsAssignableFrom (Types[i]) &&!Types[i]. IsAbstract) {//Creating Objects                        Objecto =activator.createinstance (Types[i]); //get the specified objectPropertyInfo psi= Types[i]. GetProperty ("Name"); ObjectO2=PSI.                        GetValue (o); //Add to menu bar (this is a menu bar control under WinForm)ToolStripItem tsi=PluginToolStripMenuItem.DropDownItems.Add (O2.                        ToString ()); //Registering Click eventsTsi. Tag = Types[i];//storing Data Objects in the object to be used//TSI. Click + = Tsi_click;Tsi. Click + = (s, e2) = ={Type T= TSI. Tag asType; MethodInfo mi= T.getmethod ("DoIt"); Mi. Invoke (O,New Object[] { });                    }; }                }

Summary: many. dll files can be reflected to obtain the corresponding class, the use of the method properties of the class, some applications can also be anti-compilation software to obtain some method properties, etc. (If you use it for another purpose, add it later)

C # Reflection

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.