// Define a normal CLR interface in C#.
interface IBasicMath
{
int Add(int x, int y);
}
// Implementation of IBasicMath.
class MyCalc : IBasicMath
{
public int Add(int x, int y)
{
return x + y;
}
}
Now, assume you do not have access to the code definition of IBasicMath, but wish to add a
new member (such as a subtraction method) to expand its behavior. You might attempt to author
the following extension class to do so:
static class MathExtensions
{
// Extend IBasicMath with subtraction method?
public static int Subtract(this IBasicMath itf,
int x, int y);
}
However, this will result in compile-time errors. When you extend an interface with new mem-
bers, you must
also supply an implementation of these members! This seems to fly in the face of
the very nature of interface types, as interfaces do not provide implementations, only definitions.
Nevertheless, we are required to define our MathExtensions class as follows:
static class MathExtensions
{
Do'stlaringiz bilan baham: |