namespace Feng.FramWorkDesign
{
public class IOCContainer
{
private Dictionary<Type, object> mInstance = new Dictionary<Type, object>();
public void Register<T>(T instance)
{
var key = typeof(T);
if (mInstance.ContainsKey(key))
{
mInstance[key] = instance;
}
else
{
mInstance.Add(key,instance);
}
}
public T Get<T>() where T : class
{
var key = typeof(T);
if (mInstance.TryGetValue(key,out var retInstance))
{
return retInstance as T;
}
return null;
}
}
}
-----------------------------------------------------------------------
使用方法
namespace Feng.FramWorkDesign标签:容器,container,mInstance,class,key,var,IOC,public From: https://www.cnblogs.com/TriggerF/p/17654807.html
{
public class IOCExample : MonoBehaviour
{
private void Start()
{
//创建一个IOC容器
var container = new IOCContainer();
//注册一个实例
container.Register(new BluetoothManager());
//根据类型获取实例
var bluetoothManager = container.Get<BluetoothManager>();
//实现方法
bluetoothManager.Connect();
}
}
public class BluetoothManager
{
public void Connect()
{
Debug.Log("链接成功");
}
}
}