C#_Dictionary<TKey, TValue>的使用

本文介绍了一个使用C#实现的简单示例,该示例中定义了一个Person类并使用字典来存储Person对象。通过此示例可以了解如何在C#中创建类、设置属性以及如何使用字典进行数据存储。
    class Person
    {
        private int age;
        private string name;

        public Person(int age, string name)
        {
            this.age = age;
            this.name = name;
        }

        public int Age
        {
            get
            {
                return this.age;
            }

            set
            {
                this.age = value;
            }
        }

        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                this.name = value;
            }
        }

        public override string ToString()
        {
            return string.Format("age:{0}, name:{1}", this.age, this.name);
        }
    }

    class Start
    {
        static void Main(string[] args)
        {
            Dictionary<string, Person> personDict = new Dictionary<string, Person>();
            personDict.Add("key1", new Person(25, "cxm"));
            personDict.Add("key2", new Person(24, "zqr"));
            personDict.Add("key3", new Person(27, "xiaoming"));
            foreach (var item in personDict)
            {
                Console.WriteLine(item);
                Console.WriteLine("key:" + item.Key + " value:" + item.Value);
            }
            Console.WriteLine(personDict.Count);

            Console.ReadLine();
        }
    }

C#中,可以通过多种方法获取`Dictionary<TKey, TValue>`的值。 ### 通过键直接访问 可以使用方括号`[]`通过指定键来直接访问字典中的值。示例代码如下: ```csharp using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("one", 1); dict.Add("two", 2); int value = dict["one"]; Console.WriteLine(value); } } ``` 需要注意的是,如果指定的键不存在于字典中,会抛出`KeyNotFoundException`异常。 ### 使用`TryGetValue`方法 `TryGetValue`方法可以安全地尝试获取指定键的值,避免了`KeyNotFoundException`异常。如果键存在,方法返回`true`,并通过输出参数返回对应的值;如果键不存在,返回`false`。示例代码如下: ```csharp using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("one", 1); dict.Add("two", 2); int result; if (dict.TryGetValue("one", out result)) { Console.WriteLine(result); } else { Console.WriteLine("Key not found"); } } } ``` ### 遍历字典获取所有值 可以使用`foreach`循环遍历字典的`Values`属性来获取字典中的所有值。示例代码如下: ```csharp using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("one", 1); dict.Add("two", 2); foreach (int value in dict.Values) { Console.WriteLine(value); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值