要使一个方法返回一个IDictionaryDictionary
来定义方法的返回类型。下面是一个示例代码:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
// 调用方法并输出结果
var dictionaries = GetDictionaries();
foreach (var dictionary in dictionaries)
{
foreach (var kvp in dictionary)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
Console.WriteLine();
}
}
public static Dictionary[] GetDictionaries()
{
// 创建一个IDictionary数组
Dictionary[] dictionaries = new Dictionary[2];
// 创建第一个字典并添加键值对
var dictionary1 = new Dictionary();
dictionary1.Add("A", 1);
dictionary1.Add("B", 2);
dictionary1.Add("C", 3);
dictionaries[0] = dictionary1;
// 创建第二个字典并添加键值对
var dictionary2 = new Dictionary();
dictionary2.Add("X", 10);
dictionary2.Add("Y", 20);
dictionary2.Add("Z", 30);
dictionaries[1] = dictionary2;
return dictionaries;
}
}
此示例中,GetDictionaries
方法返回一个Dictionary
数组,数组中包含两个Dictionary
字典。在Main
方法中,我们调用GetDictionaries
方法并遍历每个字典输出键值对。
输出结果:
Key: A, Value: 1
Key: B, Value: 2
Key: C, Value: 3
Key: X, Value: 10
Key: Y, Value: 20
Key: Z, Value: 30