"Adam" <
[email protected]> a écrit dans le message de (e-mail address removed)...
| I know you are not allowed to have constructors defined in an interface,
but
| why not?
This is not just a restriction in the CLR, other non-.NET languages also
don't allow this. Thinking it through, a constructor is invoked on a type,
not an instance, and it is important that this distinction is made.
Not only can you not define constructors in an interface, you cannot define
static methods either. This is for the same reason that they are not members
of an implementing object, they are members of the *type* of that object.
It may be helpful to think of this as being two classes: one for the type
and another for the instance. Delphi has the concept of a class reference,
which is essentially a "static" class, but upon which, you can call, not
only constructors and static methods, but virtual constructors and static
methods.
If you realise that constructors and static methods belong on a "reference"
class, then you can emulate the Delphi behaviour of allowing virtual
constructors and static methods by creating your own reference or metaclass.
Then, you also have the possibility of implementing an interface on the
metaclass.
Rough example :
public interface IMyInterface
{
MyClass Create();
}
public class MyClass
{
public class Reference : IMyInterface
{
public MyClass Create()
{
return new MyClass();
}
private MyClass() { }
}
public static Reference Ref
{
get { return new Reference(); }
}
}
void Test()
{
IMyInterface ref = MyClass.Ref;
MyClass cls = ref.Create();
...
}
Joanna