In c#3.0, some new features are introduced, such as: implicitly typed local variable, Extension method,lambda expression, Object initializer, Anonymous type, implicitly typed array, Query expression, expression tree. Personally, the most innovative of these new features is extension method, which fundamentally solves the problem of extending the existing type without making any changes to the definition of the type, and you can do so by doing so. Add the required method members to it. In this article, I will introduce my own understanding of the new features of extension method.
One, Prototype in JavaScript
To illustrate extension method is to solve the problem, I first give a similar, everyone is familiar with the application: JavaScript in the prototype.
For example, we define a vector class in JS through function, representing a 2-D vector.
function Vector (x,y)
{
this.x = x;
this.y = y;
}
Now we need to add the relevant method for vector operations without changing the vector definition. For example, we now need to add a adds method for two vector addition operations. 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!");
}
}
So, by adding a piece of code above, we can totally use the adds method as a method member of the vector. Now we can write code in this way:
var v = new Vector (1,2);
v= v.adds(v);
alert("x = " +v.x + ", y = "+v.y);
Extension method is in C # 3.0 just as prototype is to JavaScript.
Ii. How to solve the extensibility of type in C # 2.0
We have the exact same problem migrating from weakly typed, interpreted programming language JavaScript to a strong-typed, compiled language like C #. Let's take a look at how we solve this problem in C # 2.0, which is not a new feature of Extension method.
Let's start by looking at how to expand a interface. Suppose we have the following definition of a Ivector interface:
public interface IVector
{
double X { get; set; }
double Y { get; set; }
}
What we want to do is extend the interface to add a Adds method that performs the vector addition. Our only solution is to add a adds member directly to this interface:
public interface IVector
{
double X { get; set; }
double Y { get; set; }
IVector Adds(IVector vector);
}