有关语言设计的问题(数组和索引)

and*_*gor -2 c#

using System;
using System.Collections;

public class Program
{
    public static void Main()
    {
        Hashtable x = new Hashtable();
        string[] y = new string[]{ "hello", "world" };

        x.Add("msg", y);

        //Console.WriteLine(x["msg"][0]); why error?
        Console.WriteLine(x["msg"].GetType()); //System.String[]
        Console.WriteLine(((string[]) x["msg"])[0]);
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么我不能访问这样的数组项

Console.WriteLine(x["msg"][0]);//Cannot apply indexing with [] to an expression of type 'object'
Run Code Online (Sandbox Code Playgroud)

如果编译器知道其为字符串数组

Console.WriteLine(x["msg"].GetType());//System.String[]
Run Code Online (Sandbox Code Playgroud)

它迫使我使用这种丑陋的语法?

Console.WriteLine(((string[]) x["msg"])[0]);
Run Code Online (Sandbox Code Playgroud)

Amy*_*Amy 5

您的哈希表不是通用的。它所知道的就是附加值是类型的object

的运行时类型x["msg"]string[],但其编译时类型为object

这是HashTable索引器签名object this[object key] { get; set; }。换句话说,在编译时,使用索引器检索的任何对象都将具有编译时类型object

您可以改用泛型Dictionary<Tkey, TValue>。这将保留编译时类型信息:

var dict = new Dictionary<string, string[]>();
dict.Add("msg", new string[]{ "hello", "world" });
Console.WriteLine(dict["msg"][0]);
Run Code Online (Sandbox Code Playgroud)