我流泪了,因为我不知道该如何使用Action来初始化一个Dictionary? [英] I have tears because I don't know how to field initialize a Dictionary with Action?

查看:98
本文介绍了我流泪了,因为我不知道该如何使用Action来初始化一个Dictionary?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在具有爆炸功能的Unity项目中,您经常这样做

In Unity projects featuring explosions you often do this

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
    }

没问题,但是如果您能做到的话,那会让我很开心...

No problem, but it would make me happy if you could do this...

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

那会让我更加快乐……你知道当你睡得更好,享受微笑时享受美食的感觉吗?

That would make me much happier ... you know that feeling when you sleep better, enjoy meals with more of a smile?

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

Of course, that doesn't work because:

资产/脚本/对象/精简组/ReallyTremendousExplosions.cs(134,26):错误CS0236:字段初始化程序无法引用非静态字段,方法或属性`ReallyTremendousExplosions.SomeCall()'

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

有人能给我带来和平吗?

Can anyone bring me peace on this?

是否有一种方法可以解决您必须在初始化时执行此操作的问题?

Is there a way to get around the fact that you have to do it at initialization time?

推荐答案

SomeCall似乎是非静态方法,这就是为什么您不能在字段中使用它的原因初始化程序.但是,您可以将初始化放入构造函数:

It seems that SomeCall is a non static method and that's why you can't use it in the field initializer. However you can put the initialization into constructor:

  public class MyClass {
    ...
    // non static method
    private void SomeCall() { ... }

    private Dictionary<string, System.Action> explosions;

    public MyClass() {
      explosions = new Dictionary<string, System.Action>() {
        {"huge", SomeCall},
        {"huger", SomeCall},
      };
    }
    ...
  }

这篇关于我流泪了,因为我不知道该如何使用Action来初始化一个Dictionary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆