Vernacular C # reflection (from autumoon)

Source: Internet
Author: User

Reflection is a kind of late binding. It can be used by developers to design code with more flexibility, the cost is to spend more system resource overhead so that the application can obtain unknown information at runtime.

To put it bluntly, when writing code, the developer may not know or be unable to determine the information of some objects, so the decision is handed over to the Code itself, in the future, when necessary, the Code obtains and judges the information and responds accordingly. This method can make the code more flexible, but when you want to use reflection, you must first consider a balance between performance and flexibility, we should not blindly use it because C # provides a reflection mechanism. We should carry forward John Carmack's spirit of "extracting the 3D image performance of PCs, instead of making machines carry heavy burdens to do things of little significance as hardware gets cheaper and cheaper.

We continue with the consistent style of this series and use examples in our daily life to explain what reflection and reflection are basically used.

Let me first ask you a question: "Where does the South Korean military service used in the collection code come from ?" Apparently it was not a temporary tailor, but it was definitely a prisoner. Well, let's add a little bit of "assembly number" to see what reflection is.

One evening, a hungry and thirsty South Korean Army leader stumbled along the country path. He was not even able to hold his gun, nor knew where the team was, I had to look for a specific direction. "No action !" Two Chinese soldiers that jumped out of the grass on the side of the road shouted: the South Korean soldier was exhausted. What was the shock? At that time, he sat down on the ground. The Chinese soldiers escorted him back to the camp and reported to their superiors that they had accidentally captured a South Korean fallen soldier while patrolling nearby.

The incident was reported to head of Wang. Head of Wang was studying the combat scheme with several officers in front of the map with a magnifier. When hearing this incident, he said to the high company chief around him without a delay: "Gao Cheng, you can check it out. If there is no major problem, you can send it to the war camp in the rear." "Yes !" After receiving the command, the high company commander turned and went out.

High company commander came to a small room, and the South Korean soldier was half lying on the ground, holding the steamed bread and water that the Chinese soldier gave him in his hand, chewing in a mouthful and seeing Gao Lian grow, the eyes show tension and fear. Mr. Gao briefly introduced China's policy of treating prisoners well and began to interrogate him-Attention, reflection started!

"Where ?" "United Nations army Li chenglate Department of troops 3 Regiment 2 Platoon 1 class ."

"What is the name ?" "Smecta ."

"What task is executed this time ?" "Dive into your army position and guide the artillery to take a shot ."

......

After some soft and hard work, the senior manager master all the information of the soldier and sorted out the materials to report to the director Wang. The soldier was taken to a small room and continued to chew his steamed buns, the head of the body was changed and put into a cotton coat specially prepared for prisoners of war.

With the transcript and a full set of heads of South Korean soldiers, Mr. Gao went to the head of the South Korean Army and reported that the head of the South Korean Army smiled with a smile: "Mr. Gao, good, when your father handed you over to me, I told him to rest assured that you are a good material. How about it? I did not say wrong, huh, but you do not have to be proud, we cannot beat it, in this way, you took this line to the place of grain and asked him to break into the enemy's position overnight after changing it. Didn't the enemy want to hit us with shells? Then we should use their methods to preemptively, let the old Valley guide our army to launch a general attack in the early morning."

I put on this line with a grain of grain, and started with half a cigarette. After he sneaked into the enemy's position, he calmly pulled out the enemy's telescope for careful observation, we passed the shooting parameters to the back-end friends army via radio, successfully guided our army to achieve this major victory.

The story above is described a little more. Let's take a look at the code. First of all, we have to have an unlucky South Korean soldier as an introduction:

   1: namespace UN
   2: {
   3:     internal class SouthKoreaArmy
   4:     {
   5:         public string Name { get; set; }
   6:  
   7:         public string Search(string destination)
   8:         {
   9:             return "OK, fire!";
  10:         }
  11:     }
  12: }

Then, we use code to implement the Operations completed by the Grain Location:

   1: internal class ChineseArmy
   2: {
   3:     public static void Action(object soldier)
   4:     {
   5:         Type type = soldier.GetType();
   6:         object ziDiGu = Activator.CreateInstance(type);
   7:         MethodInfo methodInfo = type.GetMethod("Search");
   8:  
   9:         Console.WriteLine(methodInfo.Invoke(ziDiGu, new object[] { "Position" }));
  10:     }
  11: }

This code is easy to understand. In line 5, we interrogated the captured South Korean soldier and got the information and costumes he provided, and then let the old Valley dress up as a South Korean soldier with his costumes. Line 3: Look, aren't you trying to investigate me? Okay, let's get your teeth back and fix it in your way! Next, I sneaked into the local position and guided our army to initiate a general attack.

Some basic applications of reflection are shown here, such as obtaining type information, dynamically generating objects using the obtained type, and dynamically calling its method. Of course, the reflection mechanism can do more than just these things, but the goals are the same. The program obtains information and responds to the results by itself. Reflection can make your program more flexible and powerful without worrying about performance overhead!

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.