天天看點

Extension Methods (C# 3.0 concept)

http://www.codeproject.com/Articles/24948/Three-Ways-To-Extend-A-Class

Extension Methods (C# 3.0 concept)

I have to admit that I'm not actually sure how to visualize an extension method, so please be kind to me if the above diagram does not comply to UML standards.

CarExtender

 class in code:

Extension Methods (C# 3.0 concept)

 Collapse |  Copy Code

public static class CarExtender
    {
        public static void BrakeForHeavensSake(this Car c)
        {
            c.Velocity--;
            Console.WriteLine("Braked {0} to velocity {1} (with extension method)",
                c.Name, c.Velocity);
        }
    }      

CarExtender

 class is used like this:

Extension Methods (C# 3.0 concept)

 Collapse |  Copy Code

// Let's create a third car, this is a normal car.
// There has been defined an extension method to a Car object in the namespace,
// so the BreakForHeavensSake() method is "glued" to this object.
Car c3 = new Car("Mercedes-Benz");
c3.Accelerate();
c3.BrakeForHeavensSake(); // Works ok!      

繼續閱讀