10 minutes to teach you understand reflection

What is reflection?
Reflected, programmers happy, .Net programming in the field, the reflection is ubiquitous, MVC, ASP.Net , various ORM, IOC, AOP frameworks are inseparable from almost all reflection. The underlying technology used by the decompiler is not reflected, a reverse engineering.

Reflection (Reflection, System.Reflection), is .Net Framework provides a helper library data may be read and used in the described Metadata. Metadata (the Metadata), describe a variety of information dll / exe inside, known as meta data, the relay data, is described in the data (data about data), the information description data are mainly attributes (Property), used support functions such as indicating the storage location, historical data, resource discovery, documentation and so on.

Reflection advantages and disadvantages:
Advantages: Dynamic - without damage to the original program, the program may well be extended. Eg: We have such a demand, the project for the first time using a Mysql database, because the project needs to be replaced to change the situation SqlServer database. The face of the needs of this project, the traditional solution is to add a new project in SqlServer database access code, database access layer to achieve change SqlServer, and finally compile the source code and re-released.

Solution conventional sample pseudo code is as follows:

= New new IDBHelper iDBHelper the MySqlHelper. 1 ();
2 = IDBHelper iDBHelper new new SqlServerHelper ();
. 3 iDBHelper.Query ();
sample code using reflection:

ReflectionDemo namespace. 1
2 {
. 3 ///
. 4 /// reflective plant
. 5 ///
. 6 SimpleFactory public class
. 7 {
. 8 // read the configuration file
. 9 static String Private ConfigurationManager.AppSettings IDBHelperConfig = [ "IDBHelperConfig"];
10 // Get the name of dll to be loaded
. 11 static String Private IDBHelperConfig.Split DllName = ( ',') [0];
12 is required to obtain the type name //
13 private static string TypeName = IDBHelperConfig.Split ( ',') [1];
14 //
15 // instance by dynamically loading and reflection type matches the name
16 ///
. 17 ///
18 is public static IDBHelper the CreateInstance ()
. 19 {
20 is the Assembly.Load = Assembly Assembly (DllName);
21 is the type type = assembly.GetType (TypeName);
22 object oDBHelper = Activator.CreateInstance(type);
23 IDBHelper iDBHelper = oDBHelper as IDBHelper;
24 return iDBHelper;
25 }
26 }
27 }

IDBHelper iDBHelper = SimpleFactory.CreateInstance (); iDBHelper.Query (); can be achieved by reflection configuration program, can be automatically switched based achieved by modifying the configuration file, the class must implement the existing beforehand, not the implementation class is fixed, but by the configuration file is executed, created by reflection. Scalable: completely revise the existing code, just add a new realization, modify the configuration file, you can support the new features. This is the dynamic characteristics of reflection.

Disadvantages: cumbersome to use, to avoid compiler checks result in abnormal operation program line increases, and performance issues.

Reflected by calling the constructor

SqlServerDb namespace. 1
2 {
. 3
. 4 ///
. 5 /// reflection test class
. 6 ///
. 7 ReflectionTest public class
. 8 {
. 9 #region the Identity
10 ///
. 11 /// no argument constructor
12 is ///
13 is public ReflectionTest ()
14 {
15 Console.WriteLine ( "{0} here no-argument constructor", this.GetType ());
16}
. 17
18 is ///
. 19 /// constructor parameters
20 //
21 // /
22 is public ReflectionTest (string name)
23 is {
24 Console.WriteLine ( "here has parameters {0}] {string constructor", this.GetType ());
25}
26 is
27 public ReflectionTest (int ID)
28 {
29 Console.WriteLine ( "here has parameters {0} int [] constructor", this.GetType ());
30}
31 is #endregion
32
33 is #region Method,
34 is ///
35 /// method without parameters
36 / //
37 [Show1 public void ()
38 is {
39 Console.WriteLine ( "{0} here Show1", this.GetType ());
40}
41 is ///
42 is /// method has parameters
43 ///
44 ///
45 Show2 public void (int ID)
46 is {
47
48 Console.WriteLine ( "{0} here Show2", this.GetType ());
49}
50 ///
51 is overloaded methods of /// a
52 is ///
53 is ///
54 is ///
55 Show3 public void (int ID, String name)
56 is {
57 Console.WriteLine ( "{0} here Show3", this.GetType ());
58}
59 //
60 // overloads bis
61 //
62 //
63 //
64 void Show3 public (String name, int ID)
65 {
66 Console.WriteLine ( "{0} here Show3_2", this.GetType ());
67}
68 ///
69 /// overloads ter
70 ///
71 is ///
72 Show3 public void (int ID)
73 is {
74 Console.WriteLine ( "{0} here Show3_3", this.GetType ());
75}
76 ///
77 /// weight a method of carrying four
78 ///
79 ///
80 public void Show3 (String name)
81 {
82 Console.WriteLine ( "{0} here Show3_4", this.GetType ());
83}
84
85 //
86 // overloads Five
87 ///
88 Show3 public void ()
89 {
90 Console.WriteLine ( "{0} here Show3_1", this.GetType ());
91 is}
92
93 //
94 // private method
95 //
96 //
97 private void Show4 (String name)
98 {
99 Console.WriteLine ( "{0} here Show4", this.GetType ());
100}
101
102 //
103 // static method
104 //
105 //
106 public static void Show5 (String name)
107 {
108 Console.WriteLine ( "{0} here Show5", typeof (ReflectionTest ));
109}
110 #endregion
111}
112}

1 Assembly assembly = Assembly.Load(“SqlServerDb”);
2 Type type = assembly.GetType(“SqlServerDb.ReflectionTest”);
3 foreach (ConstructorInfo ctor in type.GetConstructors())
4 {
5 Console.WriteLine(KaTeX parse error: Expected '}', got 'EOF' at end of input: …sole.WriteLine(“ParameterType:{parameter.ParameterType},parameterName: {parameter.Name}”);
9 }
10 }
11 object oTest1 = Activator.CreateInstance(type);
12 object oTest2 = Activator.CreateInstance(type, new object[] { 123 });
13 object oTest3 = Activator.CreateInstance(type, new object[] { “陌殇” });

Singleton damage for
1 // singleton reflective damage - is reflected private constructor call
2 = the Assembly.Load Assembly Assembly ( "SqlServerDb");
. 3 Assembly.GetType the Type = type ( "SqlServerDb.Singleton");
. 4 = the Singleton singletonA (the Singleton) the Activator.CreateInstance (type, to true);
. 5 singletonB the Singleton = (the Singleton) the Activator.CreateInstance (type, to true);
. 6 Console.WriteLine ($ "{Object.ReferenceEquals (singletonA, singletonB)}");
a reflective call generic class

namespace SqlServerDb
{

/// <summary>
/// 泛型测试类
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="W"></typeparam>
/// <typeparam name="X"></typeparam>
public class GenericClass<T, W, X>
{
    public GenericClass()
    {
        Console.WriteLine("GenericClass<T, W, X>的构造函数被调用了");
    }


    public void Show(T t, W w, X x)
    {
        Console.WriteLine("t.type={0},w.type={1},x.type={2}", t.GetType().Name, w.GetType().Name, x.GetType().Name);
    }
}

/// <summary>
/// 泛型测试方法
/// </summary>
public class GenericMethod
{

    public GenericMethod()
    {
        Console.WriteLine("GenericMethod类的构造函数被调用了。");
    }

    public void Show<T, W, X>(T t, W w, X x)
    {
        Console.WriteLine("t.type={0},w.type={1},x.type={2}", t.GetType().Name, w.GetType().Name, x.GetType().Name);
    }

    
}

public class GenericDouble<T>
{
    public void Show<W, X>(T t, W w, X x)
    {
        Console.WriteLine("t.type={0},w.type={1},x.type={2}", t.GetType().Name, w.GetType().Name, x.GetType().Name);
    }
}

}

1 Assembly assembly = Assembly.Load(“SqlServerDb”);
2 Type type = assembly.GetType(“SqlServerDb.GenericClass`3”);
3 GenericClass<string, int, DateTime> genericClass = new GenericClass<string, int, DateTime>();
4 //genericClass.Show(“12”, 1, DateTime.Now);
5 //object oGeneric = Activator.CreateInstance(type);
6 Type typeMake = type.MakeGenericType(new Type[] { typeof(string), typeof(int), typeof(DateTime) });
7 object oGeneric = Activator.CreateInstance(typeMake);

Reflecting generic method is called
Assembly Assembly = Assembly.Load ( "SqlServerDb");
Type = Assembly.GetType of the type ( "SqlServerDb.GenericMethod");
Object oGeneric = Activator.CreateInstance (of the type);
if after reflection to create objects, know the method name , how do type conversion, directly call the method?

1 2 Assembly assembly = Assembly.Load(“SqlServerDb”);
3 Type type = assembly.GetType(“SqlServerDb.ReflectionTest”);
4 object oTest = Activator.CreateInstance(type);
5 foreach (var method in type.GetMethods())
6 {
7 Console.WriteLine(method.Name);
8 foreach (var parameter in method.GetParameters())
9 {
10 Console.WriteLine($"{parameter.Name} {parameter.ParameterType}");
11 }
12 }
13 {
14 ReflectionTest reflection = new ReflectionTest();
15 reflection.Show1();
16 }
17 {
18 MethodInfo method = type.GetMethod(“Show1”);
19 //if()
20 method.Invoke(oTest, null);
21 }
22 {
23 MethodInfo method = type.GetMethod(“Show2”);
24 method.Invoke(oTest, new object[] { 123 });
25 }
26 {
27 MethodInfo method = type.GetMethod(“Show3”, new Type[] { });
28 method.Invoke(oTest, null);
29 }
30 {
31 MethodInfo method = type.GetMethod(“Show3”, new Type[] { typeof(int) });
32 method.Invoke(oTest, new object[] { 123 });
33 }
34 {
35 MethodInfo method = type.GetMethod(“Show3”, new Type[] { typeof(string) });
36 method.Invoke(oTest, new object[] { “一生为你” });
37 }
38 {
39 MethodInfo method = type.GetMethod(“Show3”, new Type[] { typeof(int), typeof(string) });
40 method.Invoke (oTest, new object [ ] {234, " heart like no trace"});
41 is}
42 is {
43 is the Type.GetMethod the MethodInfo Method = ( "Show3", new new the Type [] {typeof (String), typeof (int)});
44 is Method.invoke (otest, new new Object [] { "the PHS", 345});
45}
46 is {
47 = the Type.GetMethod the MethodInfo Method ( "Show5");
48 Method.invoke (otest, new object [] { "Zhang Zhongkui"}); // can be a static method of example
49}
50 {
51 is the Type.GetMethod the MethodInfo method = ( "Show5");
52 is Method.invoke (null, new object [] { "Zhang Zhongkui" }); // static method examples can do
53}

Reflection to invoke a private method

1 {
2 //调用私有方法
3 Console.WriteLine("&&&&&&&&&&&&&&&&&&&&私有方法&&&&&&&&&&&&&&&&&&&");
4 Assembly assembly = Assembly.Load(“SqlServerDb”);
5 Type type = assembly.GetType(“SqlServerDb.ReflectionTest”);
6 object oTest = Activator.CreateInstance(type);
7 var method = type.GetMethod(“Show4”, BindingFlags.Instance | BindingFlags.NonPublic);
8 method.Invoke(oTest, new object[] { “我是老王” });
9 }

Reflecting generic method is called

            Assembly assembly = Assembly.Load("SqlServerDb");
            Type type = assembly.GetType("SqlServerDb.GenericMethod");
            object oGeneric = Activator.CreateInstance(type);
            foreach (var item in type.GetMethods())
            {
                Console.WriteLine(item.Name);
            }
            MethodInfo method = type.GetMethod("Show");
            //指定泛型方法的参数类型
            var methodNew = method.MakeGenericMethod(new Type[] { typeof(int), typeof(string), typeof(DateTime) });
            object oReturn = methodNew.Invoke(oGeneric, new object[] { 123, "董小姐", DateTime.Now });

Adding reflected generic method is called generic class
. 1 = the Assembly.Load Assembly Assembly ( "SqlServerDb");
2 // generic parameter types specified by type acquired while MakeGenericType
3 Type type = assembly.GetType ( "SqlServerDb.GenericDouble . 1 `") the MakeGenericType (typeof (int));.
. 4 = Object oObject the Activator.CreateInstance (type);
. 5 the Type.GetMethod the MethodInfo Method = (. "the Show") MakeGenericMethod (typeof (String), typeof (the DateTime));
6 method.Invoke (oObject, new object [ ] {345, " thank dream", DateTime.Now});

Shenzhen construction site https://www.sz886.com

Guess you like

Origin blog.csdn.net/chenmh12/article/details/91411439