// Call IBasicMath members from MyCalc object.
MyCalc c = new MyCalc();
Console.WriteLine("1 + 2 = {0}", c.Add(1, 2));
Console.WriteLine("1 - 2 = {0}", c.Subtract(1, 2));
// Can also cast into IBasicMath to invoke extension.
Console.WriteLine("30 - 9 = {0}",
((IBasicMath)c).Subtract(30, 9));
// This would NOT work!
// IBasicMath itfBM = new IBasicMath();
// itfBM.Subtract(10, 10);
Console.ReadLine();
}
That wraps up our examination of C# 2008 extension methods. Remember that this particular
language feature can be very useful whenever you wish to extend the functionality of a type, even if
you do not have access to the original source code, for the purposes of polymorphism. And, much
like implicitly typed local variables, extension methods are a key element of working with the LINQ
API. As you will see in the next chapter, numerous existing types in the base class libraries have
been extended with new functionality (via extension methods) to allow them to integrate with the
LINQ programming model.
Do'stlaringiz bilan baham: |