C # extension method learning Summary
??Copyright Notice: This article consistsQin YuanpeiCreation and publishing, usingBY)-Non-commercial use (NC)-Share in the same way(SA) The International License Agreement is licensed. For more information, see the author and source. The author of this article isQin YuanpeiThe title of this article isC # extension method learning Summary, The link of this article isHttp://qinyuanpei.com/2015/12/05/extend-methods-of-csharp/.
?? Hello everyone, I'm Qin Yuanpei. Welcome to follow my blog. Recently, I accidentally came into contact with the extension method in C #. I think this syntax feature is a good feature. So I decided to systematically summarize and sort out the content of the Extension Method in C # here, because bloggers think that learning this is a process of accumulation, they sometimes feel disgusted with online education, such as online training and video tutorials. Imagine how difficult it was to teach Guo Jing Wu Yi to experience the eight years of hard work in the legend of the Emperor? There are certainly some factors in Guo Jing's stupid nature and the weak martial arts of the Seven Monsters in the south of Jiang, but in the opinion of the bloggers, it is more important to emphasize an accumulation. If I want Guo Jing to become a hero of "for the people of the nation" in his life, I need to work harder in this world.
What is an extension method?
?? An extension method literally refers to an extension method, while an extension method provided for a class corresponds to an object-oriented programming pattern. According to our general understanding, we first need to obtain the source code of a class, and then add member methods to the class code, so that we can provide extension methods for a class. Unfortunately, this method won't work without the source code, and our manual changes to the source code may damage the stability of the entire code. Is there a way to provide extension methods for a class without changing the source code? This is the extension method we want to talk about today, so we can understand the extension method as a way to provide external extension methods without changing the source code. The Extension Method in C # is relatively simple to implement. For example, we may use the DOTween plug-in when developing Unity3D games. This plug-in is a new animation plug-in written by the author of iTween, which is much more efficient than iTween. More importantly, it adopts the extension method, which makes it hard for us to feel that we are using a plug-in when calling these API interfaces, it is more like using Unity3D native functions, so when we use a combination like DOTween + uGUI, we feel very comfortable in our hearts, and everything is just like a matter of course.
What are the characteristics of the extension method?
?? The implementation of extension methods is the same as that of common object-oriented programming. In other words, we only need to define a class and add and implement corresponding methods in it. However, there are three points to note here. First, the class that implements the extension method must be a static class and the class name has nothing to do with the class that implements the extension method; second, the class method that implements the extension method must be a static method. Third, the first parameter of the class method that implements the extension method must be the class that uses the this keyword to specify the extension method. For example, if we know to convert a valid string type to an integer type, we can use the int. parse () method. What should we do if we want to extend a ToInt method for the string type? Let's take a look at the following code:
////// 1. Define a static class. // 2. The static class name is irrelevant to the specific class to implement the extension method ///Public static class SomeClass {////// 3. Implement a specific static method //////4. The first parameter must use the this keyword to specify the type of the extension method ///
Public static int ToInt (this string str) {return int. Parse (str );}}
Note that C # supports the extension method starting with. NET3.5. Therefore, make sure that your. NET version meets this requirement when writing the extension method. When talking about the version, many friends, especially those who have been learning Unity3D since Unity5.0, often leave a message in my blog saying that my code cannot run in the new environment and so on, I think it is the fastest updated technology in the world. It is no problem for everyone to use the new version. However, sometimes due to historical issues in technological development, such as Python2.7 and Python3, Unity4.X and Unity5.X, at this time, version incompatibility may occur. If the network resources are not updated in time, we suggest you check the latest official documents in time, in the opinion of bloggers, books or related articles on the Internet are used for reference. In the old saying, it is better to believe in books than to have no books. Only by objectively and calmly judging whether the knowledge is correct or not, we can learn useful knowledge.
?? Now, after writing this extension method, you can use the extension method as follows:
string str = "1234";int val = str.ToInt();
This example shows how to compile a non-parameter extension method. What should we do when we need to input parameters in the extension method? We only need to add the parameter declaration after the first parameter. For example, in Unity3D, we often need to set coordinates for a 3D object. Generally, we can use the following code:
transform.position = new Vector3(1,1,1);
This code is concise so far, but we know that in Unity3D, there are other localPosition attributes besides the position attribute. If our Code involves coordinate calculation, I believe this code will become very long. What's more, sometimes we only want to change a dimension in 3D coordinates, but we have to give transform. position a three-dimensional coordinate, and the code will become longer without accident. To solve this problem, we can extend the three methods SetPositionX, SetPositionY, and SetPositionZ to assign values to the three coordinate components x, y, and z, respectively, we will continue to add methods in the SomeClass class:
////// Set the X coordinate of Tranform //////Current Transform ///X coordinate public static void SetPositionX (this Transform tran, float x) {tran. position = new Vector3 (x, tran. position. y, tran. position. z );}////// Set the Y coordinate of Tranform //////Current Transform ///Y coordinate public static void SetPositionY (this Transform tran, float y) {tran. position = new Vector3 (tran. position. x, y, tran. position. z );}////// Set the zcoordinate of Tranform //////Current Transform ///Zcoordinate public static void SetPositionZ (this Transform tran, float z) {tran. position = new Vector3 (tran. position. x, tran. position. y, z );}
Similarly, we can now assign values to the coordinates of a three-dimensional object directly:
transform.SetPositionX(1.0f);transform.SetPositionY(1.0f);transform.SetPositionZ(1.0f);
Advantages and disadvantages of using extension methods
?? The extension method is easy to use, so we will discuss the advantages and disadvantages of using the extension method here. The advantage is of course the ability to freely and arbitrarily use the extension method to expand the class, and the smart prompts of the Extension Method in Visual Studio will be marked with a blue downward arrow. The disadvantage of the expansion method is that the people who design the expansion method can better control this feature. In fact, all technologies are the same. I often hear people in the game group despise the Unity3D engine, I admit that UE4 has good screen effects, but how many people can really use this engine? The extension method should follow the proximity principle when using it, that is, the extension method should be used within the minimum scope to implement the Extension Method for the specific class rather than the abstract class. The extension method is nothing more than because it requires such a function in the logic layer, so we do not need to change the logic of the abstract layer, because it will "pollute" the entire code. Let's take a simple example. the base class in NET is object. If we extend this class, it will undoubtedly affect all classes inherited from the object, which will cause "pollution ", obviously, it is not advisable.
Summary in C #, the class that implements the extension method must be a static class, and the class name is irrelevant to the class that implements the extension method. The class method that implements the extension method must be a class that implements the extension method of the static method. the first parameter of the method must be the use of the this keyword to specify the class implementation Extension Method of the extension method should abide by the proximity principle, use extension methods to minimize pollution"