繁体   English   中英

是否可以创建一个字典,其中的值可以具有多种数据类型? (另外我如何遍历一个数组作为我的值之一)

[英]Is it possible to create a dictionary in which values can have multiple data types? (Also how do I iterate through an array as one of my values)

在这种情况下,如何遍历 profile["Names"]?

使用 System.Collections.Generic;

        Dictionary<object, object> profile = new Dictionary<object, object>();
        profile.Add("Names", new string[]{"Joel", "Sean"});
        profile.Add("Ethnicity", "Asian");
        profile.Add("Language", "English");

        for (int i = 0; i < profile["Names"].length; i ++)
        {
            System.Console.WriteLine($"Name: {i}");
        }
       Console.WriteLine("Ethnicity - " + profile["Ethnicity"]);
       Console.WriteLine("Language - " + profile["Language"]);

您可以在字典的键是字符串类型的情况下使用它。

当您知道它是时,我们需要将值 object 转换为字符串数组。

Dictionary<string, object> profile = new Dictionary<string, object>();
profile.Add("Names", new string[] { "Joel", "Sean" });
profile.Add("Ethnicity", "Asian");
profile.Add("Language", "English");

var names = (string[])profile["Names"];
for ( int i = 0; i < names.Length; i++ )
{
  Console.WriteLine($"Name: {names[i]}");
}
Console.WriteLine("Ethnicity - " + profile["Ethnicity"]);
Console.WriteLine("Language - " + profile["Language"]);

但是您应该考虑重新考虑您的设计,因为实际不是很干净而不是字符串类型。

也许:

using System.Collections.Generics;

public class Profile
{
  public string Name { get; set; }
  public string Ethnicity { get; set; }
  public string Language { get; set; }
  public Profile(string name, string ethnicity, string language)
  {
    Name = name;
    Ethnicity = ethnicity;
    Language = language;
  }
}

var profiles = new List<Profile>();
profiles.Add(new Profile("Joel", "Asian", "English"));
profiles.Add(new Profile("Sean", "Asian", "English"));

foreach ( var item in profiles )
{
  Console.WriteLine("Name: " + item.Name);
  Console.WriteLine("Ethnicity: " + item.Ethnicity);
  Console.WriteLine("Language: " + item.Language);
  Console.WriteLine();
}

您还可以使用枚举或查找 collections 而不是字符串来获取种族和语言:

enum Ethnicity
{
  Asian,
  Caucasian
}

enum Language
{
  English,
  French
}

现在配置文件可以是:

public class Profile
{
  public string Name { get; set; }
  public Ethnicity Ethnicity { get; set; }
  public Language Language { get; set; }
  public Profile(string name, Ethnicity ethnicity, Language language)
  {
    Name = name;
    Ethnicity = ethnicity;
    Language = language;
  }
}

像这样使用:

var profiles = new List<Profile>();
profiles.Add(new Profile("Joel", Ethnicity.Asian, Language.English));
profiles.Add(new Profile("Sean", Ethnicity.Asian, Language.English));

foreach ( var item in profiles )
{
  Console.WriteLine("Name: " + item.Name);
  Console.WriteLine("Ethnicity: " + item.Ethnicity);
  Console.WriteLine("Language: " + item.Language);
  Console.WriteLine();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM