Summary of extension method learning in C #

Source: Internet
Author: User

?? Copyright Notice : This document was authored and published by Qin Yuanpei and licensed under the Attribution (by)- NonCommercial (NC)- shared (SA) International license Agreement, Reprint please indicate the author and source, the author of this article is Qin Yuanpei , this article is titled in C # extension Method Learning Summary , this article links to http://qinyuanpei.com/2015/12/05/ extend-methods-of-csharp/.

?? Hello friends, I am Qin Yuanpei, welcome to pay attention to my blog. The recent accidental exposure to the extension method in C #, I think this syntax feature is a good feature, so decided to systematically here in C # extension method related content to summarize and collation, because bloggers feel that learning this thing itself is a process of accumulation, So bloggers sometimes resent the "online education" that is now on-line training and video tutorials. Imagine "the hero of the shoot" in Jiangnan seven strange far to the desert to teach Guo Jing martial Arts Bitter Calendar 18, why difficult and the whole true teaching Danyang son Wang teach two years of accumulation? Here is Guo Jingxian stupid nature and the South seven strange martial arts of the low factor, but in the blogger seems more important is to emphasize an accumulation. Want to Guo Jing life benefit from the Quanjin taught the dark door of the end into a generation of "attitude" of the big man, then my generation need more efforts in this world to walk.

What is an extension method?

?? Extension methods are literally referred to as extended methods, whereas the pattern of object-oriented programming refers to the extension method provided for a class. As we usually understand, we first need to obtain the source code of a class, and then add the member method in this class of code, so that we can achieve the purpose of providing an extension method to a class. Unfortunately, this approach does not work without source code, and it is possible for us to artificially change the source code to compromise the stability of the entire code. So is there a way to provide extension methods for a class without changing the source code? That's what we're going to say today, so we can understand the extension method as a way to provide external extension methods without changing the source code. The extension methods in C # are relatively simple to implement, for example, when we do the Unity3d game development, we may use the Dotween plugin. This plugin is Itween's author to rewrite an animation plugin, more efficient than the itween has a greater increase. More importantly, it takes an extension approach, which makes it difficult to feel that we are using a plugin when invoking these API interfaces, more like using Unity3d's native functions, so when we use a combination of Dotween + Ugui, The heart will feel very comfortable, everything is like a normal.

What are the features of the extension method?

?? Extension methods are implemented in the same way as normal object-oriented programming, in other words, we only need to define a class and then add and implement the appropriate method inside. But there are three points to note here, first, the class that implements the extension method must be a static class, and the name of the class is independent of the class that implements the extension method; second, the class method that implements the extension method must be a static method; The first parameter of a class method that implements an extension method must be the class that uses the this keyword to indicate the extension method to implement. For example, we know that converting a valid string type to an integer can be done using the Int.parse () method, and what if we want to extend a ToInt method for the string type? Let's take a look at the following code:

//   <summary>   ///1, define a static class  ///2, the name of the static class is independent of the specific class to implement the extension method//   </summary>  Public Static classsomeclass{//   <summary>       ///3, implementation of a specific static method    //   </summary>       /// <param name= "str" >4, the first parameter must use the This keyword to specify the type of extension method to use </param>     ///   <returns></returns>      Public Static int ToInt( This stringSTR) {return int.    Parse (str); }}

It is important to note that the C # support extension method is from the. The NET3.5 version starts, so make sure that your. NET version meets this requirement when writing extension methods. Referring to the version issue, There are a lot of friends, especially from Unity5.0 after learning Unity3d friends, often in my blog message mentions my code can not run in the new environment and so on similar issues, I think the world's fastest update is it technology, we use the new version is not a problem, but sometimes because of the history of technology development left to ask such as Python2.7 and Python3, unity4.x and unity5.x, this time may appear incompatible version of the issue, this time if the resources on the network is not updated in a timely manner, it is recommended that you still check the official latest documents, because in the blogger seems that the network of books or related articles are used for reference, the proverb says: The letter is better than no book, only objective and calmly judge whether knowledge is correct or not, we can learn the real useful knowledge.

?? Well, now that we've written this extension method, we can use the extension method as follows:

str"1234";intstr.ToInt();

This example shows you how to write a parameterless extension method, so what do we do when we need to pass in the extension method? We just need to continue with the declaration of the parameter after the first argument. For example, we often need to set coordinates for a 3D object in Unity3d, which we can usually do with the following code:

transform.position = new Vector3(1,1,1);

This code so far is relatively concise, but we know that in Unity3d in addition to the Position property there are localposition properties, if our code again involved in coordinate calculation, I believe this code will become very long. What's more, sometimes we just want to change one dimension in the three-dimensional coordinates, but we have to give transform.position a three-dimensional coordinate, and the code will get longer at this time without a surprise. To solve this problem, we can extend three methods Setpositionx, Setpositiony, and Setpositionz to assign values for x, y, z three coordinate components, and we continue to add methods to the SomeClass class:

//   <summary> ///   Set the x-coordinate of Tranform//   </summary> ///   <param name= "Tran" > current transform</param> //   <param name= "x" >x-coordinate </param>  Public Static void Setpositionx( ThisTransform Tran,floatX) {tran.position =NewVector3 (x, TRAN.POSITION.Y, tran.position.z);}//   <summary> ///   Set the y-coordinate of tranform//   </summary> ///   <param name= "Tran" > current transform</param> //   <param name= "x" >y-coordinate </param>  Public Static void Setpositiony( ThisTransform Tran,floatY) {tran.position =NewVector3 (tran.position.x, y, tran.position.z);}//   <summary> ///   set z-coordinate of Tranform//   </summary> ///   <param name= "Tran" > current transform</param> //   <param name= "x" >z-coordinate </param>  Public Static void Setpositionz( ThisTransform Tran,floatZ) {tran.position =NewVector3 (tran.position.x, TRAN.POSITION.Y, z);}

Similarly, we can now assign values directly to the coordinates of a three-dimensional object:

transform.SetPositionX(1.0f);transform.SetPositionY(1.0f);transform.SetPositionZ(1.0f);
Pros and cons of using extension methods

?? Extension methods are handy to use, so let's discuss the pros and cons of using extension methods here. The benefit is of course the freedom and willful use of extension methods to extend the class, and the smart hints for extension methods in Visual Studio are identified by a blue down arrow. The disadvantage of extension method is to see the design extension method of the person can better control this feature, in fact, all the technology is the same, I often hear people despise unity3d engine in the game group, to Unreal Engine4 for the game engine world Rohit, I admit UE4 picture effect is good, But how many people can actually use the engine well? Extension methods should be used in accordance with the nearest principle, that is, in the smallest extent using extension methods, specific classes rather than abstract classes to implement extension methods. We use the extension method simply because it requires such functionality at the logical level, so there is no need to change the logic of the abstraction layer because it "pollutes" the entire code. To give a simple example, we know. The base class in net is object, and if we extend this class, it will undoubtedly affect all classes that inherit from object, which can cause "pollution", which is obviously undesirable.

Summary
    • The class that implements the extension method in C # must be a static class and the name of the class is independent of the class that implements the extension method
    • The class method that implements the extension method must be a static method
    • The first parameter of a class method that implements an extension method must be a class that uses the this keyword to indicate the extension method to implement
    • Implementation of extension methods should adhere to the nearest principle, the use of extension methods in the smallest extent to avoid causing "pollution"

Summary of extension method learning in C #

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.