C#中的索引举例

源码:

using System;
class IndexerRecord
{
    private string[] data = new string[6];
    private string[] keys = {
        "Author", "Publisher", "Title",
        "Subject", "ISBN", "Comments"
        };

    //注:程序中用了两种方法来索引:
    //一是整数作下标,二是字符串(关键词名)作下标
    public string this[int idx]
    {
        set
        {
            if (idx >= 0 && idx < data.Length)
                data[idx] = value;
        }
        get
        {
            if (idx >= 0 && idx < data.Length)
                return data[idx];
            return null;
        }
    }
    public string this[string key]
    {
        set
        {
            int idx = FindKey(key);
            this[idx] = value;
        }
        get
        {
            return this[FindKey(key)];
        }
    }
    private int FindKey(string key)
    {
        for (int i = 0; i < keys.Length; i++)
            if (keys[i] == key) return i;
        return -1;
    }
    static void Main()
    {
        IndexerRecord record = new IndexerRecord();
        record[0] = "马克-吐温";
        record[1] = "Crox出版公司";
        record[2] = "汤姆-索亚历险记";
        Console.WriteLine(record["Title"]);
        Console.WriteLine(record["Author"]);
        Console.WriteLine(record["Publisher"]);
    }
}

运行效果如下:



C#,Dictionary是一个存储键值对的集合,它提供了快速的查找能力。Dictionary使用泛型类实现,这意味着你可以指定键和值的类型。以下是一个使用Dictionary的基本示例: ```csharp using System; using System.Collections.Generic; class Program { static void Main() { // 创建一个键为字符串,值为整数的Dictionary Dictionary<string, int> ages = new Dictionary<string, int>(); // 添加元素 ages.Add("Alice", 24); ages.Add("Bob", 25); // 检查某个键是否存在于Dictionary if (ages.ContainsKey("Alice")) { Console.WriteLine($"Alice的年龄是:{ages["Alice"]}"); } // 更新一个已存在的键的值 ages["Alice"] = 26; // 遍历Dictionary foreach (KeyValuePair<string, int> kvp in ages) { Console.WriteLine($"键:{kvp.Key}, 值:{kvp.Value}"); } // 尝试添加一个已经存在的键将会引发异常,除非使用TryAdd方法 // ages.Add("Alice", 27); // 这会引发异常 // 使用TryGetValue方法安全地尝试获取值 int age; if (ages.TryGetValue("Bob", out age)) { Console.WriteLine($"Bob的年龄是:{age}"); } else { Console.WriteLine("Bob不在字典"); } // 删除一个键值对 ages.Remove("Alice"); // 清空Dictionary ages.Clear(); // 检查Dictionary是否为空 if (ages.Count == 0) { Console.WriteLine("字典是空的"); } } } ``` 在这个例子,我们首先创建了一个名为`ages`的Dictionary实例,键是字符串类型,值是整数类型。然后,我们使用`Add`方法添加了两个键值对,使用`ContainsKey`来检查键是否存在,用索引器`[]`来更新和检索值,并且展示了如何安全地尝试获取值的`TryGetValue`方法。我们还演示了如何遍历字典、尝试添加已存在的键值对时可能会引发异常、如何删除键值对以及清空整个字典。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值