. NET Reflection

Source: Internet
Author: User

Reflection is. NET is a powerful mechanism.

It is like the demon mirror of the general existence. It can call any of your private members, such as private constructors, private methods, and private fields.

class constructor declaration for private, no one else can instantiate the object out of it? No,no,no!!!

The following shows the charm of reflection:

1 using System;
2 using System.Reflection;
3 using System.Runtime.Remoting;
4
5 namespace zuo_testreflectionprojecti{
6
7 #region "Program Entry"
8 public class program{
9 static void Main () {
Ten Console.WriteLine ("Load an assembly first, then analyze its structure:");
One by one Assembly-assembly.getexecutingassembly (); Load the current assembly
Console.WriteLine ("The name of the assembly is: {0}", ". FullName);
Console.WriteLine (New String ('-', 40));
14
15//List the included classes
Type[] TSS = to-do. GetTypes ();
+ foreach (Type ts in TSS) {
Console.WriteLine ("type name: {0}", ts. Name);
19}
20
Console.WriteLine (New String ('-', 40));
22//Individually for TestClass reflection calls
of Type Oa = the. GetType ("Zuo_testreflectionprojecti.testclass");
Console.WriteLine ("Current type name: {0}", oa.name);
25
memberinfo[] Minss = Oa.getmembers (bindingflags.instance|
bindingflags.static|
bindingflags.public|
bindingflags.nonpublic|
(bindingflags.declaredonly); Get all Members
Console.WriteLine (New String ('-', 40));
Console.WriteLine ("Member list:");
(MemberInfo mins in Minss) {
Console.WriteLine ("{0}", mins);
35}
Console.WriteLine (New String ('-', 40));
37//instantiation of a TestClass object
38
39//1. Instantiate with a public constructor, with one parameter
40//Instantiate using assembly Assembly.createinstance ()
41//First parameter: String name representing the instance of the type to be created
42//Second parameter: Description is not case-insensitive (Ignore)
43///Third parameter: Specify default here, meaning that the policy is not to use bingdingflags (you can interpret it as null, but BindingFlags is a value type, so it is not possible to be null, there must be a default value is its default value);
44//Fourth parameter: Binder, which encapsulates the rules of the CreateInstance binding object (Calculator), we almost always pass NULL in, actually using predefined defaultbinder;
45//Fifth parameter: is a object[] array type, which contains the parameters we passed in, the parameters of the constructor will use these parameters;
46//Sixth parameter: is a CultureInfo type that contains information about language and culture (simple to understand is when ToString ("C") should show "¥" and when "$" should be displayed).
47//Seventh parameter: is an object[] array that describes the attributes
48
The//ta is a TestClass object after our instantiation.
50//This is the public constructor of the call
Wuyi Object Ta = the. CreateInstance (oa.fullname,true,bindingflags.default,null,new object[]{"Mike"},null,null);
52
53//This is the private constructor of the call
54//mode is instantiated with Activator.CreateInstance (), returning an object of the ObjectHandle class
55//requires unwrap () to return object objects
Parameter description of//activator.createinstance ()
57//First parameter: The full name of the current assembly, in the form of a string
58//Second parameter: String name representing the instance of the type to be created
59//Third parameter: Description is not case-insensitive (Ignore)
60//Fourth parameter: BindingFlags
//Default, which means not to use the Bingdingflags strategy
+//NonPublic specify non-public type
63//Fifth parameter: Binder, which encapsulates the rules of the CreateInstance binding object (Calculator), we almost always pass NULL in, actually using predefined defaultbinder;
64//Sixth parameter: is a object[] array type, which contains the parameters we passed in, the parameters of the constructor will use these parameters;
65//Other parameters: ... Slightly
ObjectHandle handler = Activator.CreateInstance (NULL, oa.fullname,true,bindingflags.default|
bindingflags.instance|
(Bindingflags.nonpublic,null,null,null,null,null);
//TB is an object created from a private constructor
The object Tb = handler. Unwrap ();
71
72//Call its methods to do something
Console.WriteLine ("Call its method to do something:");
74
Oa.invokemember ("Show", bindingflags.invokemethod,null,ta,null,null,null,null);
The//pshow method is private and still has no resistance to call
Oa.invokemember ("Pshow", bindingflags.invokemethod| bindingflags.instance| Bindingflags.nonpublic,null,ta,null,null,null,null);
78
Console.WriteLine ();
Oa.invokemember ("Show", bindingflags.invokemethod,null,tb,null,null,null,null);
Bayi Oa.invokemember ("Pshow", bindingflags.invokemethod| bindingflags.instance| Bindingflags.nonpublic,null,tb,null,null,null,null);
82
Console.WriteLine ();
84//Through the property background generation method, the property is consulted once
The string str = Oa.invokemember ("Get_classname", Bindingflags.invokemethod,null,tb,null,null,null,null). ToString ();
Console.WriteLine ("TB attribute name: {0}", str);
87
Console.WriteLine ();
89//Through the property background generated method, set the property once, the property's set accessor is private
Oa.invokemember ("Set_classname", bindingflags.invokemethod| bindingflags.instance| Bindingflags.nonpublic,null,tb,new object[]{"Satan"},null,null,null);
91
Console.WriteLine ();
93//Through the property background generation method, the changed properties are reviewed again
94 str = Oa.invokemember ("Get_classname", Bindingflags.invokemethod,null,tb,null,null,null,null). ToString ();
Console.WriteLine ("TB attribute name: {0}", str);
96
The Console.WriteLine (New string ('-', 40));
98 Console.WriteLine ("Attribute:");
Oa.invokemember str = ("ClassName", Bindingflags.getproperty,null,tb,null,null,null,null). ToString ();
Console.WriteLine ("{1}" property obtained is: {0} ", str," Tb ");
101
102//This setting property is interesting
103//whole is public, and set is private, so BindingFlags need nonpublic and public, lack of one is not
104 Console.WriteLine ();
Oa.invokemember ("ClassName", bindingflags.setproperty| bindingflags.instance| bindingflags.nonpublic| Bindingflags.public,null,tb,new object[]{"vampire"},null,null,null);
106
107 Console.WriteLine ();
108 str = oa.invokemember ("ClassName", Bindingflags.getproperty,null,tb,null,null,null,null). ToString ();
109 Console.WriteLine ("{1} Property obtained is: {0}", str, "Tb");
110
111 Console.WriteLine (New String ('-', 40));
Console.WriteLine ("Direct access or set private field:");
113 String field = Oa.invokemember ("ClassName", bindingflags.getfield| bindingflags.instance| Bindingflags.nonpublic,null,tb,null,null,null,null). ToString ();
Console.WriteLine ("Tb s private string classname:{0}", field);
115
116//Directly set private fields in the class
117 Oa.invokemember ("ClassName", bindingflags.setfield| bindingflags.instance| Bindingflags.nonpublic,null,tb,new object[]{"The Blood of the Asura"},null,null,null);
118
119 Console.WriteLine ("\ n Reset:");
* field = Oa.invokemember ("ClassName", bindingflags.getfield| bindingflags.instance| Bindingflags.nonpublic,null,tb,null,null,null,null). ToString ();
121 Console.WriteLine ("Tb s private string classname:{0}", field);
122
123 Console.WriteLine ();
124 Console.WriteLine ("Reflection Makes your code invisible, if your code does not do some defensive measures.") ");
125}
126}
127 #endregion
128
129 #region "class to be called for reflection"
The public class TestClass
131 {
ClassName private string;
133
134 Private TestClass ()
135 {
136 This.classname = "Abyss Demon";
137}
138
139 public TestClass (string n) {
This.classname = n;
141}
142
143 public void Show () {
144 Console.WriteLine ("ClassName is:{0}", This.classname);
145}
146
147 private void Pshow () {
148 Console.WriteLine ("Evil Fellow, you should not call this method.") Its name is: {0} ", this.classname);
149}
150
151 public string classname{
get{return this.classname;}
153 Private set{Console.WriteLine ("Calling the private property set, breaking the rules of the guy is really annoying!") "); this.classname=value;}
154}
155
156}
157 #endregion
158}

Code Run Result:

D:\a>otherroad
Load an assembly first and then analyze its structure:
The name of the assembly is: Otherroad, version=0.0.0.0, Culture=neutral, Publickeytoken=null
----------------------------------------
Type name: Program
Type name: TestClass
----------------------------------------
Current type name: TestClass
----------------------------------------
Member List:
Void Show ()
Void Pshow ()
System.String Get_classname ()
Void Set_classname (System.String)
Void. ctor ()
Void. ctor (System.String)
System.String ClassName
System.String ClassName
----------------------------------------
Call its methods to do something:
ClassName is: Mike
Evil Fellow, you should not call this method. Its name is: Mike.

ClassName is: Abyss Demon
Evil Fellow, you should not call this method. Its name is: Abyss Demon

TB attribute name: Abyss Demon

Calling the private property set, the guy who broke the rules is really annoying!

TB attribute Name: Satan
----------------------------------------
Property:
The properties that are obtained by TB are: Satan

Calling the private property set, the guy who broke the rules is really annoying!

The properties that are obtained by TB are: Vampires
----------------------------------------
Directly access or set private fields:
Tb ' s private string className: Vampire

After re-setting:
Tb ' s private string className: The blood of the Asura

. NET 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.