<hu*******@yahoo.comwrote in message
news:11**********************@b28g2000cwb.googlegr oups.com...
An interface defines just a contract and not the implementation itself.
So if the static keyword would be allowed for a function then it would
only say that the class implementing the interface must declare this
function as static. Therefore, unless I missed something I think your
argument is not valid.
The "interface as a contract" is a useful concept, but not 100% correct.
Really, an interface is a restricted abstract class, with all functions
being pure virtual and no data. So the interface has a v-table layout which
needs to be followed by implementing classes, just like an abstract class
has a v-table layout used by subclasses.
Now, just like the Region class has a static member function Union which
operates on a group of Region objects, MSIL allows an interface to have
static member functions and properties which are generally useful and
applied to the entire tree of class types implementing that interface.
For example, if an interface declared an instance Guid property, it would be
useful to have a static method which returns the instance (of some derived
type) given the Guid. This static method is part of the interface type, and
not a contractual constraint on implementors.
The static keyword consistently means "part of the declaring type, not part
of any object". Thus you can see that an abstract static method is
impossible.
To get something like static methods on derived types, you can borrow from
COM's playbook. In COM implementations in C (not C++), you had to set up
the object's v-table by declaring a structure of function pointers. You can
do the same, by having a class of delegate fields. The interface declares a
property with that class type. Each implementing class needs to initialize
one copy of this class in the type initializer, to point to its set of
static methods, and then the (instance) property just returns the static
field which refers to the delegate group.
Something like:
class RequiredStaticMethods
{
public readonly EventHandler a;
public readonly EventHandler b;
public RequiredStaticMethods(EventHandler a, EventHandler b)
{
if (a == null || b == null) throw new ArgumentNullException();
this.a = a;
this.b = b;
}
}
interface INeedStaticMethods
{
RequiredStaticMethods StaticMethods { get; }
}
class AnImplementation : INeedStaticMethods
{
private static void OnA(object sender, EventArgs e) {}
private static void OnB(object sender, EventArgs e) {}
public static readonly RequiredStaticMethods StaticMethods = new
RequiredStaticMethods(OnA, OnB);
RequiredStaticMethods INeedStaticMethods.StaticMethods { get { return
StaticMethods; } }
}
now you can call:
AnImplementation.StaticMethods.a(...);
INeedStaticMethods x = new AnImplementation(); // call static method of
fixed type
x.StaticMethods.b(...); // dynamic dispatch to static method based on
runtime type of x