Can you force a method to be called inside a class constructor, else throw compile error?
I have a class, Player, which inherit开发者_如何学运维s from AnimatedSprite. AnimatedSprite has a protected abstract method, loadAnimations, which Player must override to load the actual animations (since animations will vary based on the sprite image, it needs to be implemented by the class deriving from AnimatedSprite).
However, while I force the class user to implement the method, is there a way to force the user to actually call this method, preferably inside the Player constructor, to ensure that the animations are always loaded? I'm pretty sure C# doesn't have any language features to do this (though I could be wrong), so perhaps there's a better class design pattern that I can implement which I'm overseeing?
As always, thanks in advance!
It is actually not recommended to call virtual methods in a constructor, since they may use state that is not yet initialized (the relevant constructor has not yet been called).
Personally I would just had an abstract method that you call after the constructor, maybe via a factory:
static T Create<T>() where T : TheBase, new()
{
T obj = new T();
obj.Init();
return obj;
}
i think that calling methods inside constructor is not a good approach...
i'm used to do this way:
public abstract class AnimatedSprite
{
public void LoadAnimations()
{
OnLoadAnimations();
}
protected abstract void OnLoadAnimations();
protected virtual void OnNextFrame() { };
....
}
I'm assuming AnimatedSprite
is an abstract class. Just add the call to the method inisde AnimatedSprite
's constructor.
精彩评论