Unity 关于接口带泛型参数的使用

背景

开发过程中,接口式开发很常见,但是,接口中有时会附带一些参数,对于新手来说,有时候会有些迷惑,所以写了一个简单的样例。Mark一下。

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum ActionType
{
    Idle,
    Walk,
    Run,
}
public class Test22 : MonoBehaviour
{
    private FlyMaganger _flyMg;
    // Start is called before the first frame update
    void Start()
    {
       _flyMg= new FlyMaganger();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            foreach (var temp in _flyMg.Dic.Values)
            {
                temp.Des();
            }
        }
    }
}
public class FlyMaganger : FlyManagerBase<ActionType>
{
    public FlyMaganger() : base()
    {
    }

    public override void InitAction()
    {
        AddActionHandler(ActionType.Idle,new Fly(ActionType.Idle));
        AddActionHandler(ActionType.Walk, new Fly(ActionType.Walk));
        AddActionHandler(ActionType.Run, new Fly(ActionType.Run));
    }
}
public abstract class FlyManagerBase<TAction> : IFlyManager<TAction>
{
    public Dictionary<TAction, IFly<TAction>> Dic { private set; get; }
    public void AddActionHandler(TAction actionLabel, IFly<TAction> fly)
    {
        Dic.Add(actionLabel,fly);
    }
    public abstract void InitAction();
    public FlyManagerBase()
    {
        Dic = new Dictionary<TAction, IFly<TAction>>();
        InitAction();
    }
}

public interface IFlyManager<TAction>
{
    void AddActionHandler(TAction actionLabel,IFly<TAction> fly);
}
public class Fly: FlyBase<ActionType>
{
    public Fly(ActionType a):base(a)
    {
    }
    public override int Count()
    {
        return UnityEngine.Random.Range(1,1000);
    }

    public override void Des()
    {
        Debug.LogError(Count()+"只小鸟在"+tAction);
    }
}
public abstract class FlyBase<TAction> : IFly<TAction>
{
    public FlyBase(TAction tAction)
    {
        this.tAction = tAction;
    }
    public TAction tAction { get;set; }
    public abstract int Count();
    public abstract void Des();
}
public interface IFly<TAction>
{
    TAction tAction { get; set; }
    void Des();
    int Count();
}

 

 

  

 

posted @ 2020-12-25 16:05  低小调  阅读(371)  评论(0编辑  收藏  举报