在c#中,字典与哈希表是一样的。
口述记录有点像数组,您可以其中自定义默认索引编号,使其更有意义,下面是一个示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dictionary
{
class Program
{
static void Main(string[] args)
{
// 我们创建一个空字典 CountriesAndCapitals
// 索引,是一个字符串,主值也是一个字符串
Dictionary<string, string=> CountriesAndCapitals = new Dictionary<string, string=>();
// 将项目添加到字典中
CountriesAndCapitals.Add("England","London");
CountriesAndCapitals.Add("France","Paris");
CountriesAndCapitals.Add("Italy","Rome");
Console.WriteLine(CountriesAndCapitals["Italy"]);
}
}
}
字典非常强大,它经常被用来创建一个字典,其中键是string,但值本身实际上是一个自定义对象,要实例化这种类型的对象,我们需要:
Dictionary {Dictionary’s Name} = new Dictionary();
现在常见的做法是创建一个自定义类,我们将使用它创建填充字典所需的自定义对象。一个(静态)方法(由主程序触发),该方法依次实例化dictionary对象,然后该方法实例化自定义类中的许多对象,并将它们与键一起添加到dictionary中。最后,该方法将字典返回给它的调用者,调用者将在字典变量中捕获它。
下面是一个实际的例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dictionary
{
class Program
{
static void Main(string[] args)
{
// 在这里,我们调用CountryStat类的(静态)GetCountryListInfo方法,
// 以便生成字典、填充字典,然后返回字典:
var RetrievedCountryInfo = CountryStat.GetCountryListInfo();
Console.WriteLine
(
"England has a population of {0} and it’s official language is {1}. It’s capital city is called {2}.",
RetrievedCountryInfo["England"].Population,
RetrievedCountryInfo["England"].
Language,RetrievedCountryInfo["England"].Capital
);
}
}
public class CountryStat
{
public string Capital { get; set; }
public int Population { get; set; }
public string Language { get; set; }
public CountryStat(string Capital, int Population, string Language)
{
this.Capital = Capital;
this.Population = Population;
this.Language = Language;
}
// 我们实例化字典,并向字典中添加条目
public static Dictionary<string, CountryStat=> GetCountryListInfo()
{
// 我们创建将填充的空字典:
Dictionary<string, CountryStat=> DictionaryOfCountries = new Dictionary<string, CountryStat=>();
// 我们创建要添加到字典的第一个对象:
CountryStat EnglandObject = new CountryStat("London", 60000000, "English");
// 将此对象添加到字典
DictionaryOfCountries.Add("England",EnglandObject);
// 我们创建要添加到字典的下一个对象:
CountryStat FranceObject = new CountryStat("Paris", 90000000, "French");
// 将此对象添加到字典:
DictionaryOfCountries.Add("France",FranceObject);
// 创建要添加到词典的下一个对象:
CountryStat RussiaObject = new CountryStat("Moscow", 180000000, "Russian");
// 将此对象添加到字典:
DictionaryOfCountries.Add("Russia",RussiaObject);
// 将填充的字典返回给调用者:
return DictionaryOfCountries;
}
}
}
日期:2020-07-07 20:54:26 来源:oir作者:oir
