簡體   English   中英

如何從 C# 中的其他類的函數訪問字典?

[英]How to access Dictionary from other Class's function in C#?

我創建了一個名為“EngDictionary”的類。 然后我在函數中定義了一個字典,例如:

public void Dict()
    {
        Dictionary<string, string> d = new Dictionary<string, string>();
        d.Add("Classifieds", "Kleinanzeigen");
        //d.Add("windows", 5);   
    }

現在我想從我的主類訪問上面定義的字典來檢索我的字典的鍵和值。 請建議我一些代碼。 我使用的是 Visual C# 2008 Express Edition,Win 應用程序

將 Dictionary 聲明為類屬性。

public class Dict {

   private Dictionary<string, string> dict;
   public SomeDictionary { get dict; set dict = value; }

   public Dict() {
      dict = new Dictionary<string, string>();
      dict.Add("Classifieds", "Kleinanzeigen");
   }
}

在其他班級:

Dict d = new Dict();
string test = d.SomeDictionary["Classifieds"];
Console.WriteLine(test);

從方法返回字典。

public Dictionary<string, string> Dict() {.... ; return d;}

在你的主班。

EngDictionary dict = new EngDictionary();
Dictionary<string, string> dictionary = dict.Dict();

您可以將Dictionary<string, string> d聲明為您的類的成員變量,並在類構造函數中初始化此對象。您可以使用 getter 方法來獲取其他類中的字典。

public class EngDictionary
{
    Dictionary<string, string> dictionary;
    public void EngDictionary()
   {
        dictionary = new Dictionary<string, string>();
        dictionary.Add("Classifieds", "Kleinanzeigen");
        ....
    }

   public Dictionary<string, string> getDictionary()
   {
         return this.dictionary;
   }

 }

我有一堂課

 public class Dict
    {
        public Dictionary<string, string> SomeDictionary { get; } = new Dictionary<string, string>()
        {
            { "Classifieds", "Kleinanzeigen" }
        };
    }

然后在任何其他班級

  Dict Dic = new Dict();
            
            foreach (var item in Dic.SomeDictionary)
            {
                Console.WriteLine(item.Key);
                Console.WriteLine(item.Value);
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM