Constructor has not a generic name but the same name as class so there is a syntax problem 开发者_运维技巧to enforce them in interface class. What's the syntax then for something like this:
Interface IInterface {
<class-name-of-implementer>(string param) {}
}
The problem I see with creating an initialize method is that client app of your framwork/library can just forget to call it ! Seems to me that if constructor was just named __Constructor like in some other languages that would be possible so it's not possible just because of syntax !
Syntax should not drive design but semantics.
You can't, I'm afraid.
Generally speaking, you wouldn't be able to use such a constructor anyway - how would you expect to invoke it? You can enforce a parameterless constructor on a type parameter, like this:
public class Foo<T> where T : new()
but you can't specify any required parameters.
I've previously suggested that it would be useful to be able to specify static members (including constructors) in interfaces, solely for type constraints (and to use them the members in expressions based on those constrained type parameters). See my blog post for more details.
You can't do this. Your best bet would be
interface IInterface
{
void Initialize(string param);
}
where Initialize does some initialization work (if this is what you're after).
Constructors are not allowed in interfaces.
A workaround would be to put an initialize() method in the constructor and do all the constructor related stuff here. Messy but that's all you can do.
精彩评论