[英]Does C# have array with index is a string like PHP?
I have been learning C# myself for 2 months. 我一直在学习C#2个月。 Before, I learned PHP and see that it has an array where the index is a string, like this:
之前,我学习了PHP,看到它有一个数组,索引是一个字符串,如下所示:
$John["age"] = 21;
$John["location"] = "Vietnam";
It is very useful to remember what we set to an array element. 记住我们设置为数组元素的内容非常有用。 I tried to find if C# supports that array type, but I haven't seen any answers, yet.
我试图找出C#是否支持该数组类型,但我还没有看到任何答案。
Does C# have an array like this? C#有这样的数组吗? If it does, how can I create it?
如果有,我该如何创建它?
C# supports any type of object for an index. C#支持索引的任何类型的对象。 A baked-in implementation is
System.Collections.Generic.Dictionary<T1,T2>
. 一个带烘焙的实现是
System.Collections.Generic.Dictionary<T1,T2>
。 You can declare one like this: 你可以这样声明一个:
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
Yes, this is an associative array, represented in C# by the generic Dictionary<TKey, TValue>
class or the non-generic Hashtable
. 是的,这是一个关联数组,由C#中的泛型
Dictionary<TKey, TValue>
类或非泛型Hashtable
。
Your code would be only possible with a Hashmap
as the values are not all of the same type. 您的代码只能使用
Hashmap
因为值不是全部相同的类型。 However, I strongly suggest you re-think that design. 但是,我强烈建议你重新考虑一下设计。
Use a System.Collections.Generic.Dictionary<T1,T2>
as other said. 使用
System.Collections.Generic.Dictionary<T1,T2>
如其他所说。 To complete your knowledge, you should know that you can control yourself the behavior of the []
. 为了完成你的知识,你应该知道你可以控制自己
[]
的行为。 Exemple : 例如:
public class MyClass
{
public string this[string someArg]
{
get { return "You called this with " + someArg; }
}
}
class Program
{
void Main()
{
MyClass x = new MyClass();
Console.WriteLine(x["something"]);
}
}
Will produce "You called this with something". 会产生“你称之为”。
More on this in the documentation 在文档中有更多相关内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.