繁体   English   中英

如何通用传递 class 作为参数

[英]How to generic pass class as parameter

public class Skeleton : MonoBehaviour
{
    private MonsterBaseState state;
    private void Awake()
    {
        state = new PatrolState<Skeleton>(this);
    }
    public void  GetMonsterInfo()
    {
      dosomething;
    }
}
pubilc class manyMonster:MonoBehaviour 
{
    private MonsterBaseState state;
    private void Awake()
    {
        state = new PatrolState<Skeleton>(this);
    }
}
//and more monster Class

public interface MonsterBaseState
{
    void BehaviorForUpdate();
}
public class PatrolState<T> : MonsterBaseState
{ 
    private T cluster;
    public PatrolState(T curCluster)
    {
        cluster = curCluster;
        cluster.GetMonsterInfo();//wrong here
    }
        public void BehaviorForUpdate()
    {
    }
}

我不能在 PatrolState Class 中使用 GetMonsterinfo 方法

我想通过骷髅或者其他怪物,所以不用写很多状态码

您可以实现一个新接口,如下所示:

public interface IMonster
{
    void GetMonsterInfo();
    //void MonsterMethod1();
    //void MonsterMethod2();
    //..
}

public class Skeleton : MonoBehaviour,IMonster
{
    private MonsterBaseState state;
    private void Awake()
    {
        state = new PatrolState<Skeleton>(this);
    }
    public void  GetMonsterInfo()
    {
       
    }

}


public interface MonsterBaseState
{
    void BehaviorForUpdate();
}
public class PatrolState<T> : MonsterBaseState where T :IMonster
{ 
    private T cluster;
    public PatrolState(T curCluster)
    {
        cluster = curCluster;
        cluster.GetMonsterInfo();//wrong here
    }
    
    public void BehaviorForUpdate()
    {
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM