C # expansion method)

Source: Internet
Author: User
Some new column features are introduced in C #3.0, such as implicitly typed local variable, extension method, Lambda expression, object initializer, anonymous type, implicitly typed array, query expression, expression Tree. I personally think that the extension method is the most innovative in this series of new features. It fundamentally solves the problem: to expand the existing type while it remains intact, you can add the required method member for the type definition without any changes. In this article Article .

I. Prototype in Javascript

To illustrate how the extension method solves the problem, I first give an application similar to the prototype in Javascript that everyone is familiar.

For example, we define a Vector class through function in JS, representing a 2-dimensional vector.

Function vector (x, y)
{
This. x = X;
This. Y = y;
}

Now we need to add the relevant method for vector calculation without changing the definition of the vector. For example, we need to add an adds Method for adding two vectors. In JS, we can easily implement this function through prototype:

Vector. Prototype. Adds = function (V)
{
If (V instanceof vector)
{
Return new vector (this. x + v. X, this. Y + v. y );
}
Else
{
Alert ("invalid vector object! ");
}
}

Then, add the preceding SectionCodeWe can use the adds method as a member of the vector method. Now we can write the code in this way:

VaR v = new vector (1, 2 );
V = V. Adds (v );
Alert ("x =" + v. x + ", y =" + v. y );

Extension Method in C #3.0 is like prototype in JavaScript.

Ii. How to Solve type scalability in C #2.0

We have the same problem from weak type, interpreted typeProgramming LanguageJavascript is migrated to C #, a strongly typed and compiled language. Let's take a look at how we solve this problem in C #2.0, which does not support the new extension method feature.

Let's first look at how to expand an interface. Suppose we have the following definition of an ivector interface:

Public interface ivector
{
Double X {Get; set ;}
Double Y {Get; set ;}
}

We hope to extend this interface and add an adds method to it to execute the vector addition operation. The only solution is to add an adds member directly in this interface:

Public interface ivector
{
Double X {Get; set ;}
Double Y {Get; set ;}
Ivector adds (ivector vector );
}

The interface is closely related to the type to implement it: Therefore, all methods to implement the interface must be implemented for the type of an interface. Therefore, we have added the adds method, which will cause all the types that implement it to be redefined and compiled. In many cases, we cannot afford this cost: for example, in the later maintenance phase of the system, partial and full re-Compilation of the system will lead to a normal system crash. This limitation of interface should be fully considered in abstract design and programming. This is also a major reason why we prefer abstract class in many cases.

As mentioned above, the interface extension may lead to the risk that the interface type must be modified. I think some people will say that class extension won't happen. Yes, the inheritance of the class ensures that the public/protect we add in the parent class can be inherited by the Child class. For example, if the vector is a super class:

Public class Vector
{
Private double _ x;
Private double _ y;

Public Double X
{
Get {return this. _ x ;}
Set {This. _ x = value ;}
}

Public Double Y
{
Get {return this. _ y ;}
Set {This. _ y = value ;}
}
}

If we add an adds Method to the Vector class, all child classes will not be affected.

However, in many cases, we cannot make any changes to the interface or type that we need to expand. For example, a type is defined in an assembly provided by a third party. In the current situation, we can't do anything about such a requirement. The common method is to inherit the extended class defined by ourselves, and define the Members to be added in the class defined by ourselves. What should we do for a sealed class? Even if it is not sealed class, this method does not meet our predefined requirements: What we want is to extend this unchangeable type, that is, the instance of the unchangeable type has the object we added.

If you hear this requirement when you fully understand the extension method: we need to extend a type or interface, but we cannot modify it. This requirement is indeed a little harsh. However, it is undeniable that such applications need to be widely used in reality. So I said that the extension method is of great value among all the new features provided.

Iii. How to resolve type scalability in C #3.0

After understanding our specific needs and the limitations of the existing programming language, let's take a look at how C #3.0 solves this problem through the extension method.

In short, extension method is a special static method defined in static class. This static method is special because extension method can be called not only according to the static method syntax, but also according to the instance method syntax.

Let's take a look at the example. First, we need to define the extended vector type:

Public class Vector
{
Private double _ x;
Private double _ y;

Public Double X
{
Get {return this. _ x ;}
Set {This. _ x = value ;}
}

Public Double Y
{
Get {return this. _ y ;}
Set {This. _ y = value ;}
}
}

Without updating the definition of Vector class, we define the adds method to be added in a static class:

Public static class Extension
{
Public static vector adds (this vector p, vector P1)
{
Return new vector {x = p. x + p1.x, y = P. Y + p1.y };
}
}

This extension method: adds is a static method. Unlike the general static method, this keyword is added before the first parameter. This is the keyword introduced when the extension method is defined in C #3.0. After such a keyword is added, the parameter marked with this can be prefixed when the method is called, allowing us to call the static method by calling the General instance method. For example:

Class Program
{
Static void main (string [] ARGs)
{
VaR v = new vector {x = 1, y = 2 };
V = V. Adds (v );
Console. writeline ("V. x = {0} and V. Y = {1}", V. X, V. y );
}
}

Note: This keyword can only be used to mark the first parameter.

Through the above introduction, we know how to extend the type without making any changes to the type by defining the Extension Method in C #3.0.

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.