C # Learning Note (10): Reflection

Source: Internet
Author: User

Reflection

Emission is the mechanism of dynamically acquiring the information of a class while the program is running, and we look at the reflection in C # below.

Type

Type is the root of the System.Reflection feature and is the primary way to access metadata. Use the members of type to get information about the type declaration, such as constructors, methods, fields, properties, and events for the class, and the modules and assemblies in which the class is deployed.

We have three ways to get a type of the specified types:

    1. Direct access through TypeOf;
    2. Obtained by invoking the GetType method;
    3. obtained by invoking the static method of type GetType;

Each of the three methods can get a type object of the specified types, but there is a little difference, depending on the following two blogs:

Http://www.studyofnet.com/news/284.html

http://blog.csdn.net/letianok/article/details/7257117

Let's look at an example:

1 usingSystem;2 3 namespaceStudy4 {5     class Program6     {7         Static voidMain (string[] args)8         {9Type T1 =typeof(string);Ten Console.WriteLine (t1. FullName); One             //System.String A  -Type t2 ="Hello type!". GetType (); - Console.WriteLine (T2. FullName); the             //System.String -  -Type t3 = Type.GetType ("System.String",false); - Console.WriteLine (T3. FullName); +             //System.String -  + Console.read (); A         } at     } -}
Get information about a class

We can get all the information of the class by type, for example, if we want to get all the method information of the class, we can use the following code:

1 usingSystem;2 usingSystem.Reflection;3 4 namespaceStudy5 {6     class Program7     {8         Static voidMain (string[] args)9         {Ten             stringstr ="Hello type!"; One  AType T =Str. GetType (); -             //Get all method information -methodinfo[] Methodinfos =t.getmethods (); the              for(inti =0; i < methodinfos.length; i++) -             { - Console.WriteLine (Methodinfos[i]. Name); -             } +             //get non-static public method information only -Methodinfos = T.getmethods (bindingflags.instance |bindingflags.public); +              for(inti =0; i < methodinfos.length; i++) A             { at Console.WriteLine (Methodinfos[i]. Name); -             } -  - Console.read (); -         } -     } in}

More information can be obtained by referencing the Help documentation (Https://msdn.microsoft.com/zh-cn/library/system.type (v=vs.110). aspx).

Invokes the specified method

Let's look at how to get a specified method of a class and make a call:

1 usingSystem;2 usingSystem.Reflection;3 4 namespaceStudy5 {6     class Program7     {8         Static voidMain (string[] args)9         {Ten             stringstr ="Hello type!"; One  AType T =Str. GetType (); -             //for a method that has multiple overloads, you need to indicate the type of the parameter -MethodInfo method = T.getmethod ("Split",New[]{typeof(Char[])}); the             //Calling Methods -             string[] STRs = method. Invoke (str,New Object[] {New[] {' '}}) as string[]; -              for(inti =0; I < STRs. Length; i++) -             { + Console.WriteLine (Strs[i]); -             } +  A Console.read (); at         } -     } -}
Assembly

An assembly can be seen as a collection of one or more DLLs or EXE files that can be reused by extracting duplicate code from an assembly.

We first create a class library project with the following code:

1 namespaceStudylib2 {3      Public classMyClass4     {5          Public intADD (intAintb)6         {7             returnA +b;8         }9 Ten          Public intADD (intAintBintc) One         { A             returnA + B +C; -         } -     } the}

Then click on the menu bar-"Generate-" Generate XXX, you can get the corresponding DLL file, next we use assembly read the DLL and execute the method in it:

1 usingSystem;2 usingSystem.Reflection;3 4 namespaceStudy5 {6     class Program7     {8         Static voidMain (string[] args)9         {TenAssembly Assembly = Assembly.LoadFrom ("E:\\study\\c#\\studylib\\studylib\\bin\\debug\\studylib.dll"); One  A             //output all type names -type[] Types =Assembly. GetTypes (); -              for(inti =0; I < types. Length; i++) the             { - Console.WriteLine (Types[i]. FullName); -             } -             //Studylib.myclass +  -             //dynamically create classes and Invoke methods in them +Type t = assembly. GetType ("Studylib.myclass"); AConstructorInfo constructor =T.getconstructor (type.emptytypes); atObject MyClass = constructor. Invoke (New Object[]{}); -  -MethodInfo method1 = T.getmethod ("ADD",New[] {typeof(int),typeof(int)}); -             intRESULT1 = (int) method1. Invoke (MyClass,New Object[] { -,123}); -Console.WriteLine ("The first method returns:"+result1); -             //The first method returns: 223 in  -MethodInfo method2 = T.getmethod ("ADD",New[] {typeof(int),typeof(int),typeof(int)}); to             intRESULT2 = (int) Method2. Invoke (MyClass,New Object[] { -,123,456 }); +Console.WriteLine ("The second method returns:"+result2); -             //The second method returns: 679 the  * Console.read (); $         }Panax Notoginseng     } -}

C # Learning Note (10): 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.