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
{
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 : IFlyManager
{
public Dictionary> Dic { private set; get; }
public void AddActionHandler(TAction actionLabel, IFly fly)
{
Dic.Add(actionLabel,fly);
}
public abstract void InitAction();
public FlyManagerBase()
{
Dic = new Dictionary>();
InitAction();
}
}
public interface IFlyManager
{
void AddActionHandler(TAction actionLabel,IFly fly);
}
public class Fly: FlyBase
{
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 : IFly
{
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 { get; set; }
void Des();
int Count();
}