Kac*_*acy 0 c# inheritance casting
我觉得我应该只需要一个实例变量引用一个对象.但在下面的代码中,我有两个实例变量"_character"和"_witch"引用同一个对象.如果我添加一个更专业的巫婆类,我必须添加第三个实例变量.
这通常是人们在这种情况下做的事情吗?或者有没有办法只使用一个参考来实现这一目标?另外,我真的不想抛出任何东西(除非这确实是这种情况下的最佳实践).
在扩展AnimationController的WitchAnimationController之上,WitchState扩展了CharacterState.
基类:
public class AnimationController 
{
    protected CharacterState _character;
    public AnimationController( CharacterState character )
    {
        _character = character;
    }
    public void UpdateAnimations() 
    {
        /* call on some CharacterState functions... */
    }
}
Run Code Online (Sandbox Code Playgroud)
儿童班:
public class WitchAnimationController : AnimationController
{
    protected WitchState _witch; //inherits from CharacterState
    public AnimationController( WitchState witch ) : base( witch ) 
    {
        _witch = witch;
    }
    public void UpdateAnimations() 
    {
        base.UpdateAnimations();
        /* call on some WitchState functions... */
    }
}
Run Code Online (Sandbox Code Playgroud)
    如果你不需要特定于巫婆的电话,你可以放弃该_witch领域并使用该_character领域 - 尽管我个人将其作为一个受保护财产的私人领域.
如果您需要特定于角色的成员,则应考虑使动画控制器具有通用性:
public class AnimationController<T> where T : CharacterState
{
    protected T _character;
    public AnimationController(T character)
    {
        _character = character;
    }
    public void UpdateAnimations() 
    {
        /* call on some CharacterState functions... */
    }
}
Run Code Online (Sandbox Code Playgroud)
然后:
public class WitchAnimationController : AnimationController<WitchState>
{    
    public WitchAnimationController(WitchState witch) : base(witch) 
    {}
    public void UpdateAnimations() 
    {
        base.UpdateAnimations();
        _character.SomeMethodOnWitchState();
    }
}
Run Code Online (Sandbox Code Playgroud)
该_character.SomeMethodOnWitchState()呼叫在内部有效,WitchAnimationController因为_character它实际上是类型WitchState.
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           79 次  |  
        
|   最近记录:  |