【问题标题】:C# Access dictionary from different classC#访问来自不同类的字典
【发布时间】:2021-11-02 20:12:13
【问题描述】:

我一直在使用字典进行一个项目,但遇到了问题。 在我的一个 wpf 类(表单)中,我创建了一个字典,里面有一些东西。在我的第二堂课中,我想从那本字典中阅读,所以我将字典的修饰符设置为“public”。还有问题。我的字典给出了错误:CS0050: Inconsistent accessibility: return type 'Dictionary<int, CachedSound>' is less accessible than field 'LoadAudioForm.noteValue'。有谁知道如何解决这个问题?

这是我第一堂课的一部分代码:

public partial class LoadAudioForm : Form
{
    public Dictionary<int, CachedSound> noteValue = new Dictionary<int, CachedSound>();

private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        var worker = sender as BackgroundWorker;
        for (int i = 36; i < 97; i++)
        {
            noteValue.Add(i, new CachedSound("E:/VirtualCarillon/VirtualCarillon/VirtualCarillon/VirtualCarillon/Audio/01/" + i + ".wav"));
        }

现在是第二课:

AudioPlaybackEngine.Instance.PlaySound(LoadAudioForm.noteValue[ne.NoteNumber + (Convert.ToInt32(nVelR) * 100)]);

【问题讨论】:

标签: c# dictionary naudio


【解决方案1】:

看起来您正在访问 dictionary,就像它是 static 变量一样,但事实并非如此。

如果符合您的逻辑,您可以将dictionary 更改为静态。

public static Dictionary<int, CachedSound> noteValue =
    new Dictionary<int, CachedSound>();

【讨论】:

  • 这似乎对我不起作用。和以前一样的错误。
【解决方案2】:

正如错误所说:字段的类型比字段本身更难访问。

该字段为public,因此该字段的类型必须至少为public,否则编译器会抱怨这种不一致。

代码中的字段类型是Dictionary&lt;int, CachedSound&gt;;我们知道Dictionaryintpublic,所以检查CachedSound 的访问修饰符并确保它不是internalprivate

【讨论】:

  • 是的,这就是问题所在。我的 CachedSound 类没有任何修饰符,所以我将其更改为 public,这样就解决了问题。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
相关资源
最近更新 更多