【问题标题】:Alternate name for object instances stored in array, C#存储在数组中的对象实例的备用名称,C#
【发布时间】:2013-06-10 05:18:12
【问题描述】:

我有 2 个相同类型的对象实例。 (准确地说,这是 Unity3D 的 AudioSource)我需要对两者都应用一些操作,如初始化、销毁等,所以我认为将它们存储在数组中是一个好主意,这样我就可以迭代了。

AudioSource[] audioSources = new AudioSource[2];

有了这个,我可以在数组上foreach 并且只编写一次初始化代码和其他常见任务。

但这两个实例有不同的用途,例如,第一个是用于 BGM 的 AudioSource,第二个是用于 SFX。这样代码将更具可读性,我仍然可以使用数组遍历两个实例。

所以我认为我应该为每个实例指定一个备用名称,例如 bgmSource 和 sfxSource。请问这样的做法正确吗?

AudioSource bgmSource = audioSources[0];
AudioSource sfxSource = audioSources[1];

【问题讨论】:

  • 这没有错。但是,如果您不打算拥有更多它们,您也可以省去数组,而只需制作/调用子例程,如Initialize(AudioSource src)。我认为两个函数调用至少与数组上的 foreach 一样干净,它消除了对每个对象有多个引用的复杂性。

标签: c# arrays unity3d instance


【解决方案1】:

另一个解决方案是使用字典,它不太适合这么小的数组 但它可以帮助您区分对象而不使用第二个变量来存储引用 到数组中的那个。

例如:

    Dictionary< string, AudioSource > audioSources;

    audioSources = new Dictionary<string, AudioSource> 
    { 
        "BGM_SOURCE", new AudioSource(),
        "SFX_SOURCE", new AudioSource()
    };

然后您也可以使用枚举来跟踪字典键,而不是使用字符串/常量值:

// Enum declaration
enum AudioSourceNames
{
    BGM_SOURCE,
    SFX_SOURCE
}


// Called before first update
public void Start()
{
    // Dictionary declaration
    Dictionary< int, AudioSource > audioSources;

    audioSources = new Dictionary< int, AudioSource > 
    { 
        ( int )BGM_SOURCE, new AudioSource(),
        ( int )SFX_SOURCE, new AudioSource()
    };


    // Accessing the dictionary
    audioSources[ ( int )AudioSourceNames.BGM_SOURCE ].Play();
}

顺便说一句:您可以将枚举器技术与数组一起使用,这样您就不必记住数组中的每个 AudioSource 索引

【讨论】:

    【解决方案2】:

    在我看来,您的解决方案似乎不错。

    只初始化一次代码和其他常见任务

    这些东西的代码希望在 AudioSource 中,不是吗?

    【讨论】:

      【解决方案3】:

      嗯,这是合法的。这只是偏好/设计的问题。我会说你可以把它们放在某种字典里。因此,您可以通过key 正确标记它们。这样您就不需要记住 [0] 是 bgmSource 和 [1] 是 sfxSource。

      【讨论】:

        猜你喜欢
        • 2019-11-03
        • 2021-10-22
        • 2011-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-09
        • 1970-01-01
        相关资源
        最近更新 更多