gpt4 book ai didi

c# - 泛型 Unity C#

转载 作者:太空宇宙 更新时间:2023-11-03 22:35:44 27 4
gpt4 key购买 nike

如果我有一些管理器(单例),其中有一些协程,我想用一个简单的方法停止所有协程。是否可以创建一个通用类型来阻止所有传入的管理器?

我无法让它工作,但它是这样的吗?

void StopAllCorountinesInAllManager<T>(T manager)
{
manager.instance.StopAllCorountines();
}

StopAllCoruntinesInAllManager(manager1);
StopAllCoruntinesInAllManager(manager2);
StopAllCoruntinesInAllManager(manager3);

最佳答案

给你的泛型方法一个类型提示:

void StopAllCoroutinesInAllManager<T>(T manager) where T : GameObject
{
manager.StopAllCorountines();
}

通过传递实例来调用它:

StopAllCoroutinesInManager(manager1.Instance);

或者,如果您的管理器不是 GameObjects,则创建一个接口(interface),例如:

public interface IManager
{
void StopAllCoroutines();
}

并像这样更改您的通用方法:

void StopAllCoroutinesInAllManager(IManager manager)
{
manager.StopAllCorountines();
}

然后在您的管理器类中实现接口(interface)并让实现停止所有协程。但在这种情况下,您可以直接在管理器上调用 StopAllCoroutines。

这应该允许您遍历管理器列表并停止所有协程。

将管理器的实例传递给您的函数。

关于c# - 泛型 <T> Unity C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55214902/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com