2013-03-25 60 views
0
public abstract class State<T> 
{ 
    public virtual Enter(T item) 
    { 
      // an empty method 
    } 
} 

public class ChaseState : State<FieldPlayer> 
{ 
    public override Enter(Player pl) 
    { 
     // ... 
     pl.Fsm.CurrentState = ChaseState.Instance; 
     //... 
    } 
} 

public class TendGoal : State<Goalkeeper> 
{ 
    public override Enter(Goalkeeper gk) 
    { 
     // ...implementation 
     gk.Fsm.CurrentState = TendGoal.Instance; 
     // ...implementation 
    } 
} 

public class DefendState : State<Team> 
{ 
    public override Enter(Team team) 
    { 
     // ....  
     team.Fsm.CurrentState = DefendState.Instance; 
     //..... 
    } 
} 

“守门员”和“FieldPlayer”继承自抽象类“Player”,而“Team”继承自另一个类。C#存储泛型状态

public class FSM 
{ 
    public /*some type*/ owner;   // PROBLEM 1 
             // OWNER CAN BE TEAM, GOALKEEPEEPER 
             // OR FIELD PLAYER 
    public /*some type*/ globalState; 
    public /*some type*/ currentState; 
    public /*some type*/ previousState; 
    public void Update() 
    { 
     if (globalState != null) 
     { 
      globalState.Execute(owner); // PROBLEM 2 
             // IF GLOBAL STATE'S TYPE 
             // IS AN OBJECT, CANT CALL EXECUTE 
             // OBJECTS TYPE WILL BE KNOWN ONLY 
             // DURING RUNTIME 
     } 
    } 
} 

“守门员”,“FieldPlayer”和“Team”类型的每个对象都有一个状态机实例。问题是...泛型不能成为属性。

我该怎么办?

+0

我应该改变整个设计,如果是的话,怎么样? – Orvel 2013-03-25 15:12:12

+0

它看起来不像你的抽象类需要是通用的。您可以使抽象类只是一个普通的对象,并在每个对象中实现该抽象类。然后,您可以将状态类型属性添加到您的FSM类。在阅读更多内容之后,您实际上需要将State设置为一个普通的Interface,因为您在抽象类中没有做基础工作。 – 2013-03-25 15:15:24

+0

@CalebKeith我将如何覆盖具有不同参数的虚拟方法? – Orvel 2013-03-25 15:18:30

回答

0

如果你使状态成为一个普通的接口,而不是通用的,并且让它的Enter方法接受你的团队,守门员,玩家等所有的接口实现(它甚至可以是空的),它应该工作。

public interface IOwner {} 

public interface IState 
{ 
    void Enter(IOwner item); 
} 
public class ChaseState : IState 
{ 
    public void Enter(IOwner pl) 
    { 
     // ... 
     //... 
    } 
} 
public class Player :IOwner { } 
public class Something { 
    IOwner owner = new Team(); 
    IState globalState = new ChaseState(); 
    IState currentState = new DefendState(); 

    public void Update() 
    { 
     if (globalState != null) 
     { 
      globalState.Enter(owner); 
     } 
     else if (currentState != null) 
     { 
      currentState.Enter(owner); 
     } 
    } 
} 
0

在阅读你的代码之后,抽象类在这里是不必要的。您应该将状态转换为接口,例如:IState,并从中删除通用签名。然后你的FSM对象中的属性都可以是公开的IState全局状态等。