像这样使用C#数组myArray ["Name"] ="Some Name"; [英] Using C# Arrays like this myArray["Name"] = "Some Name"
本文介绍了像这样使用C#数组myArray ["Name"] ="Some Name";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是C#编程的新手,所以如果这是愚蠢的问题,请原谅我,但是我已经在Google上搜索了,但找不到答案.
我的问题是我想以这种方式使用数组:
myArray["Name"] = "Some Name";
然后得到这样的值:
varName = myArray["Name"];
我曾经在PHP中做到这一点,但在C#中却没有.
有人可以帮我吗?
提前谢谢.
最好的问候.
Hi, i''m new in C# programming, so please forgive me if this is stupid question but i''ve searching on google and i can''t find the answer.
My issue is that i want to use an array in this way:
myArray["Name"] = "Some Name";
and then get the value like this:
varName = myArray["Name"];
I used to do that in PHP, but in C# don''t.
Can anybody give me a hand on this?
Thanks in advance.
Best regards.
推荐答案
您可以使用字典.这里是一个例子:
使用System.Collections.Generic;
字典< string,> temp =新字典< string,>();
如果(temp.ContainsKey("Name"))
temp.Remove("Name");
temp ["Name"] =某些名称";
MessageBox.Show(temp ["Name"]);
you can use dictionary. Here, is an example :
using System.Collections.Generic;
Dictionary<string,> temp = new Dictionary<string,>();
if (temp.ContainsKey("Name"))
temp.Remove("Name");
temp["Name"] = "Some Name";
MessageBox.Show(temp["Name"]);
这是不可能的.
数组不能像这样使用.
如果要通过字符串
而不是数字编制索引,则必须使用其他方法:
1.索引器(公共字符串this [string key] {get; set;}
);
2. ADictionary<string,>
;
3. AStringDictionary
;
4. AHashTable
;
5.您自己的实现.
This is not possible.
Arrays can''t be used like this.
If you want to index bystring
instead of number, you have to use something else:
1. An indexer (public string this[string key] { get; set; }
);
2. ADictionary<string,>
;
3. AStringDictionary
;
4. AHashTable
;
5. Your own implementation.
如果愿意创建自定义集合类,则可以这样做.不过,使用Dictionary
可能会更容易(更快).
You could do it that way, if you''re willing to create a custom collection class. It would probably be easier (and faster) to use a Dictionary
, though.
这篇关于像这样使用C#数组myArray ["Name"] ="Some Name";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文