Reflection is a powerful mechanism within a high-level language. C # also provides us with a powerful reflection mechanism. Reflection is very simple to use, and the most common steps are:
1, defines a type object, type MyType;
2, initialize the object through a string or other stream, MyType = Type.GetType ("MyClass");
When the Type.GetType () method executes, how does the system find the correct class definition based on the string? Look at the code below
[C-sharp]View PlainCopy
- Using System;
- Using System.Collections.Generic;
- Using System.Reflection;
- Using System.IO;
- Namespace test{
- Public Delegate Object twoint32s (Int32 N1, Int32 n2);
- Public Delegate Object onestring (String s1);
- Class APP
- {
- public static void Main (string[] args)
- {
- //type deltype = Type.GetType ("twoint32s");//Wrong Call method
- Type Deltype = Type.GetType ("test.onestring"); Correct method of invocation
- if (Deltype = = null)
- {
- Console.WriteLine ("Invalid deltype argument:" + "twoint32s");
- return;
- }
- }
- }
- }
This code shows that type.gettype when parsing a type, if the parameter string does not specify namespace will cause the program not to parse the type correctly.
If we remove the namespace, we get the following code.
[C-sharp]View PlainCopy
- Using System;
- Using System.Collections.Generic;
- Using System.Reflection;
- Using System.IO;
- Public Delegate Object twoint32s (Int32 N1, Int32 n2);
- Public Delegate Object onestring (String s1);
- Class APP
- {
- public static void Main (string[] args)
- {
- Type Deltype;
- Deltype = Type.GetType ("System.IO.File"); Correct method
- //deltype = Type.GetType ("File");//Error
- Deltype = Type.GetType ("twoint32s"); Correct method of invocation
- //type deltype = Type.GetType ("test.onestring");
- if (Deltype = = null)
- {
- Console.WriteLine ("Invalid deltype argument:" + "twoint32s");
- return;
- }
- }
- }
This means that if a type is contained within a namspace, the type information must be obtained using the full path containing the namespace.
C # Reflection when the GetType method looks for the analysis of type