你能做到阵列可以使用阵列在C#中被accesed [ '名称']
array['Name'];
在C#
不是相反:
array[0];
我知道你能做到这一点的PHP但有C#的一个equivelent,尽管即时通讯思想highley不可能:(
你能做到阵列可以使用阵列在C#中被accesed [ '名称']
array['Name'];
在C#
不是相反:
array[0];
我知道你能做到这一点的PHP但有C#的一个equivelent,尽管即时通讯思想highley不可能:(
它在C#中称为Dictionary
。使用泛型你可以实际索引任何类型。像这样:
Dictionary<Person, string> dictionary = new Dictionary<Person, string>();
Person myPerson = new Person();
dictionary[myPerson] = "Some String";
...
string someString = dictionary[myPerson];
Console.WriteLine(someString);
这明显打印出“Some String”给控制台。
这是字典的灵活性的示例。你可以用一个字符串作为索引来完成,就像你所要求的一样。
Dictionary<string, whatyouwanttostorehere> myDic =
new Dictionary<string, whatyouwanttostorehere>();
myDic.Add("Name", instanceOfWhatIWantToStore);
myDic["Name"];
TY ...尼斯.... – 2010-04-22 04:28:21
这就是我的意思很抱歉,它没有显示出来完全第一次。 – 2010-04-22 04:31:52
数组不一样,在C#中的工作,但你可以一个索引属性添加到任何类:
class MyClass
{
public string this[string key]
{
get { return GetValue(key); }
set { SetValue(key, value); }
}
}
然后,你可以写陈述的类型你问对这样的:
MyClass c = new MyClass();
c["Name"] = "Bob";
这是如何实现基于字符串的索引访问Dictionary<TKey, TValue>
,NameValueCollection
和NameValueCollection
和类似的类。您可以实现多个索引,以及,例如,一个用于索引和一个名字,你只需要添加另一个属性与上面不同的参数类型。
内置多种框架类已经有这些索引,包括:
SortedList<TKey, TValue>
Dictionary<TKey, TValue>
SortedDictionary<TKey, TValue>
NameValueCollection
Lookup<TKey, TValue>
(在System.Linq
)...等等。这些都是为轻微不同的目的而设计的,因此您需要阅读每一个,并查看哪一个适合您的需求。
感谢,对laters要命的答案....:d – 2010-04-22 15:44:08
叶氏,看看'System.Collections' http://msdn.microsoft.com/en-us/library/system.collections.aspx – xandercoded 2010-04-22 04:28:40
@xandercoded,你可能想'System.Collections.Generic'。 'System.Collections'是.NET的非通用形式1. – Kobi 2010-04-22 04:32:53
谢谢........:d – 2010-04-22 15:40:32