C # extension method and use of

GPS platform, site construction, software development, system operation and maintenance, to find a large forest network technology!
http://cnsendnet.taobao.com
from Sen Science and Technology official blog
http://www.cnsendblog.com/index.php/?p=476

Extension method allows you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension method is a special kind of static method, but can be called as an instance method on the same type of expansion. These are the msdn official website description of the extension method, and now I have to explain this conduct by the example of a scene. Suppose a console program class Program {} which main function is as follows:

static void Main(string[] args)
{
DateTime now = DateTime.Now;
string time = now.ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(time);
Console.ReadKey();
}

Suppose demand has changed, the display format of the date to become "yyyy-MM-dd" format, can be rewritten by the following wording course initialized only Time:
String = now.ToString Time ( "yyyy-MM-dd" );
but if you want to change the date format there are many like it? Each must be changed again? Once such demand they change the opinions of people too busy. The traditional solution is to package a helper class, in which write method, and for other types of calls.
Add a mimic of the present embodiment in the current project DateHelper class: public class DateHelper {}, which is defined in the class methods:
public static String dateToString (the DateTime dt)
{
return dt.ToString ( "the MM-dd-YYYY HH: mm: SS") ;
}
Thus the main function of the original rewritten as follows:

static void Main(string[] args)
{
DateTime now = DateTime.Now;
string time = DateHelper.DateToString(now);
Console.WriteLine(time);
Console.ReadKey();
}

At this point if needs change, you only need to rewrite DateHelp class of DateToString () method on the line, no matter how many classes call this method, will be affected. Solve the problem, but this class to call another method, or a bit of trouble, there is no way to make us like now.DateToString () as a direct call it? Of course, Microsoft is DateTime written, we can not change, can not create an instance method you want, so it leads to extension methods.
The following is an element extension method:
1. The method must be a static method
2. This method must be placed in a static class
3. The first parameter of this method must start with this, and this method is extended to specify which type from
The more elements, we changed DateHelper class static class: public static class DateHelper {}, while rewriting dateToString () method:
public static String dateToString (the this the DateTime dt)
{
return dt.ToString ( "the mM-dd-YYYY HH: mm: SS ");
}
. In this case the method returns to the main function thereof, input" now "will be seen to have a dateToString automatically prompt () method, and the code can be written like this:

static void Main(string[] args)
{
DateTime now = DateTime.Now;
string time = now.DateToString();
Console.WriteLine(time);
Console.ReadKey();
}

Obviously, this will be more convenient to use them, and so let us look just like being an instance method itself has the same type of expansion, highly readable. The following summarize the characteristics of an extension method:
1. extension method which extends from the type, it must be this type of variable to use other types can not be used, in this case extends from DateTime type, it can only be a variable of type DateTime out. (now.DateToString ())
parameter behind this extension method 2. the parameters of the method are not, the present embodiment is no parameter, the latter is specified in this DateTime dt extending method from what type
3. If extension methods and examples methods have the same signature, the priority call instance method
4. the extension method from the parent class, the object can be used directly subclasses
5. extends from the interface, the object can be directly implemented class
6. the method final extension or the compiler into: static class static method (), in this case now.DateToString () will eventually be compiled into DateHelper.DateToString (now), which is its essence
in fact, we may encounter scenarios, such as a method in an interface extension of time, all of the already class that implements the interface methods must achieve the new extension, this change is a very Tired of work, you can use extension methods "Quxianjiuguo"; and sometimes we want to add new methods to a class of this class do not want to change, then this way of extension methods "pseudo-added" approach would reflect the value of its . The most common method is to extend LINQ standard query operators, the extensive use of this convenient and efficient way to code farmers who should win 1024 points praise.

What is an extension method?
  Extension Method literally refers to a method of expansion, and this corresponds to the object-oriented programming pattern refers to a method of spreading class. According to our usual understanding, we first need to get the source code for a class, and then add the members of this class method in the code, so that you can achieve the purpose of providing an extension method for a class. But unfortunately, this method in the source code is not the case you can not work, and we went to artificially change the source code is likely to undermine the stability of the entire code. Is there a way to provide a way to extend a class without changing the source code of the premise of it? This is an extension method we want to say today, so we can extend the method to understand method provides a way to expand to the outside without changing the source code of the premise. Extension methods in C # to implement is relatively simple, such as we do in Unity3D game development, it may be used DOTween this plugin. This plugin is iTween the author to rewrite an animation plug-in, iTween there than on efficiency greatly improved. More important point is that it uses extension methods to achieve such a way that when we call these API interface is difficult to feel that we are using a plug-in, more like using Unity3D native function, so when we use DOTween + uGUI this combination when the heart will feel very comfortable, everything fall into place like a general.
Extension Methods What are the characteristics?
  Extension method implemented in object-oriented programming and normal is the same, in other words, we only need to define a class, and then add the appropriate method may be implemented in it. But where there are three points to note here. First, the implementation class extension methods must be independent of the name of the class and static class and extension methods to achieve class; second, a class method implement extension methods must be static method; third, the first parameter class method implement extension methods must be specified using this keyword method to achieve the expansion of class. For example, we know that a legitimate string converted to an integer type, you can use int.parse () method, if we want to extend a ToInt method for the string type should be how to do it? Together we look at the following code:

  1. /// <summary>
  2. /// 1, the definition of a static class
  3. /// 2, static class name and the specific class to achieve the extension method is independent
  4. /// </summary>
  5. public static class SomeClass
  6. {
  7. /// <summary>
  8. /// 3, to achieve a specific static method
  9. /// </summary>
  10. /// <param name = "str"> 4, using the first parameter must be used to specify the type of this keyword extension method </ param>
  11. /// <returns></returns>
  12. public static int ToInt(this string str)
  13. {
  14. return int.Parse(str);
  15. }
  16. }
    Note that the C # supports extension method is to start with .NET3.5 version, so when writing an extension method, make sure your .NET version meets this requirement. Mentioned version, there are a lot of friends, especially after Unity5.0 start learning from Unity3D friends, the message often mentioned my code does not run in a new environment, etc. Similarly question in my blog, I think this world the update was undoubtedly the fastest IT technology, we use the new version no problem, but sometimes because of historical issues such as technology development and Python2.7 Python3, Unity4.X and Unity5.X, this may occur when version incompatibility issues, this time if the resources on the network is not up to date, suggest that you check out the official date documentation in a timely manner, because it seems bloggers related articles or books on the network are used to refer to the ancient saying: do letter book as no book, only objectively, dispassionately determine the correct knowledge or not, we can only learn really useful knowledge.
      Well, now after we finished writing this extension method, you can use extension methods such as the following:
  17. string str = "1234";
  18. int val = str.ToInt ();
    this example to show you how to write a extension method with no arguments, so when we need to pass parameters in the extension method how to do it? We just need to continue to add parameters in a statement after the first argument enough. For example, we often need to coordinate a 3D object disposed in Unity3D usually we may be implemented by the following code:
    transform.position Vector3 new new = (1,1,1);
    This code is relatively simple so far, but we Unity3D know that in addition to the position property there localPosition property, if our code again involved in coordinate calculation, I believe that the code will become very long. What is more, sometimes we just want to change a dimension of the three-dimensional coordinates, but we have to give a three-dimensional coordinate transform.position, not surprisingly, at this time the code will be longer. To solve this problem, we can extend the three methods SetPositionX, SetPositionY, SetPositionZ respectively as x, y, z coordinates of the three components assignment, we continue adding methods SomeClass this class:
  19. /// <summary>
  20. /// set the X coordinate of Tranform
  21. /// </summary>
  22. /// <param name="tran">当前Transform</param>
  23. /// <param name="x">X坐标</param>
  24. public static void SetPositionX(this Transform tran, float x)
  25. {
  26. tran.position = new Vector3(x, tran.position.y, tran.position.z);
  27. }
  28. /// <summary>
  29. /// set the Y coordinate Tranform
  30. /// </summary>
  31. /// <param name="tran">当前Transform</param>
  32. /// <param name="x">Y坐标</param>
  33. public static void SetPositionY(this Transform tran, float y)
  34. {
  35. tran.position = new Vector3(tran.position.x, y, tran.position.z);
  36. }
  37. /// <summary>
  38. /// set the Z coordinate Tranform
  39. /// </summary>
  40. /// <param name="tran">当前Transform</param>
  41. /// <param name="x">Z坐标</param>
  42. public static void SetPositionZ(this Transform tran, float z)
  43. {
  44. tran.position = new Vector3(tran.position.x, tran.position.y, z);
  45. }
    Using the extended method pros and cons of
      extension methods handy to use, so we are here to discuss the pros and cons of using a lower extension methods. Of course, the benefits of a free and willful use extension methods to extend the class and extension methods in Visual Studio smart tips will be identified by a blue down arrow. Downside extension method is to look at the design of the extension methods people can better manage this feature you, in fact, all the techniques are the same, I often hear people despise Unity3D game engine in the group to UnReal Engine4 game Mount Rushmore engine world, I admit UE4 good picture effect, but can really make good use of this engine, how many people do? When using extension methods should follow the principle of proximity, that is, the use of extension methods in the smallest scope, extension methods to achieve specific class rather than an abstract class. We use the extension method simply because it requires such a function at the logical level, so we do not need to change the logical abstraction layer, as this entire code "pollution." To take a simple example, we know that .NET base class is object, if we extend the class, there is no doubt it will affect all inherited from the object's class, which would cause "pollution" is obviously not desirable of.
    Summary
    • implementation class extension methods in C # must be a static class and the class name and the realization of extension methods class has nothing to do
    • class way to extend implementation of the method must be a static method
    the first parameter • implementation class method extension methods must be use this keyword to specify the class implement extension methods
    • implement extension methods should comply with the principle of proximity, use a minimum range extension methods in order to avoid "contamination"

GPS platform, site construction, software development, system operation and maintenance, to find a large forest network technology!
http://cnsendnet.taobao.com
from Sen Science and Technology official blog
http://www.cnsendblog.com/index.php/?p=476

Guess you like

Origin blog.51cto.com/14036626/2482943