字符串作为C#中的索引器

本文关键字:索引 字符串 | 更新日期: 2023-09-27 18:27:19

让我从显示代码开始:

public class Collection
{
    private object[] values;
    public Collection(int size) => values = new object[size];
    public object this[string index] 
    { 
        get => values[index]; 
        set => values[index] = (object)value;
    }
} 
public class Program
{
    private static void Main()
    {
        Collection collection = new Collection(3);
        collection["integer"] = 123;
        collection["decimal"] = 456.78;
        collection["text"]    = "Hello World!";
        double total = (double)(int)collection["integer"] + (double)collection["decimal"];
        Console.WriteLine("Total is {0}", total);
        Console.WriteLine();
        Collection collection2 = new Collection(2);
        collection2["integer"] = 123;
        collection2["decimal"] = 456.78;
        collection2["text"]    = "Hello World!"; // This wont be added because of limit
    }
}

我在做这个教程,Program类已经给了我,我不能修改它。我需要做的是创建Collection类,所以Collection类是我自己制作的。但Indexer有这个问题,因为它是string,它的工作方式似乎与以前教程中整数索引器的工作方式不同。有没有一种方法可以使用字符串作为索引器,或者我应该考虑不同的方法?此外,不允许添加命名空间。我已经被这个教程卡住一个星期了。

字符串作为C#中的索引器

您可以使用字典集合:

Dictionary<string, object> dict = new Dictionary<string, object>();
dict["hello"] = "world";

为了给你指明正确的方向,(你正在学习,所以我不想泄露它)让Collection存储两个数组,一个object[]string[]。看看这是否能让你走上正确的方向。

如果您需要进一步的提示,请点击此链接。

您需要将string[]中的字符串名称存储在与object[]中存储对象相同的索引中。如果调用var intIndex = Array.IndexOf(stringCollection, index),则可以将其结果用作return values[intIndex]

看看你是否可以在不关注链接或先看上面的剧透文本的情况下找到答案

不使用字典。。。

这存储一个对象数组和字符串数组。字符串数组用作索引器,对象数组用作值。键和值存储在它们各自阵列中的相同位置。

这里有很多优化和改进。。。但这应该是一个起点。

class Collection
{
    int size;
    int items;
    string[] keys;
    object[] values;
    public Collection(int size)
    {
        keys = new string[size];
        values = new object[size];
        this.size = size;
        items = 0;
    }
    public object this[string index]
    {
        get
        {
            int position = -1;
            for (int i = 0; i < size ; i++)
                if (keys[i] == index)
                    position = i;
            if (position == -1)
                throw new ArgumentException("Index Not Found");
            return values[position];                
        }
        set
        {
            int position = -1;
            for (int i = 0; i < size; i++)
                if (keys[i] != null && keys[i] == index)
                    position = i;
            if (position != -1)
            {
                values[position] = value;
            }
            else
            {
                if (items == size)
                    throw new Exception("Collection full");
                keys[items] = index;
                values[items] = value;
                items++;
            }
        }
    }
}

您可以使用以下方法,与您提到的方法略有不同,但效果非常好。

using System;
namespace ass5
{
    class Session
    {
        string[] values;
        string[] key;
        int i=0;
        public Session(int size)
        {
            values = new string[size];
            key=new string[size];
        }
        public string this[string index]
        {
            get
            {
                
               // i++;
                int intIndex = Array.IndexOf(key, index);
                if(intIndex==-1)
               {
                   return " error";
               }
                
                return values[intIndex];
            }
            set
            {
               key[i]=index; // for index string storage
               i++;
               int intIndex= Array.IndexOf(key, index);
               
               values[intIndex] = value; // for value corresponding to that index
            }
        }
    } 
    class Program
    {
        static void Main(string[] args)
        {
            Session session=new Session(5);
            session["username"]="user";
            session["password"]="password"; 
            Console.WriteLine(session["username"]);
        }
    }
}

您可以按如下方式使用您的类。检查ContainsKey是一个很好的做法

class Collection
{
    Dictionary<string, object> values = new Dictionary<string, object>();
    public object this[string index]
    {
        get
        {
            if(values.ContainsKey(index)
            {
              return values[index];
            }
            return null;
        }
        set
        {
            if(!values.ContainsKey(index)
            {
              values.Add(index, value);
            }
        }
    }
}