gpt4 book ai didi

c# - 我流泪了,因为我不知道如何用 Action 现场初始化 Dictionary?

转载 作者:行者123 更新时间:2023-11-30 15:22:42 31 4
gpt4 key购买 nike

在以爆炸为特色的 Unity 项目中,您经常这样做

private Dictionary<string, System.Action> explosions;

void .. initialize in your class constructor .. ()
{
explosions = new Dictionary<string, System.Action>();
explosions.Add("huge", SomeCall);
explosions.Add("huger", SomeCall);
etc
}

没问题,但如果你能做到这一点我会很高兴......

private Dictionary<string, System.Action> explosions =
new Dictionary<string, System.Action>()
{
{"huge", SomeCall},
{"huge", SomeCall},
etc
};

那会让我更快乐……您知道当您睡得更好、带着更多微笑享受美食时的那种感觉吗?

当然,这是行不通的,因为:

Assets/scripts/objects/flite groups/ReallyTremendousExplosions.cs(134,26): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `ReallyTremendousExplosions.SomeCall()'

谁能帮我解决这个问题?

有没有办法绕过必须在初始化时执行此操作的事实?

最佳答案

我喜欢字典初始化器,而且我一直都在使用它们。我感觉到你的眼泪。

答案就在你的问题中,使用委托(delegate)!

public class ReallyTremendousExplosions
{
private delegate void ExplosionFactory(ReallyTremendousExplosions source);

private Dictionary<string, ExplosionFactory> Explosions = new Dictionary<string, ExplosionFactory>()
{
{ "huge", x => x.SomeMethod() },
{ "huger", x => x.SomeMethod() }
};

private void SomeMethod()
{
//Render massive explosions...
}

public void RenderNamedExplosion(string explosionName) {
ExplosionsFactory explosionFactory;
if (!Explosions.TryGet(explosionName, out explosionFactory) {
throw new NoSuchExplosionException(explosionName);
}

explosionFactory(this);
}
}

代码在 Unity5/Mono 中经过全面测试

关于c# - 我流泪了,因为我不知道如何用 Action 现场初始化 Dictionary?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35342919/

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