2010-11-19 57 views
1

在C#中有什么东西可以像下面的<key, string, string>那样我可以使用快捷键来访问第二个和第三个字段。简单构造如下

+0

什么问题? – 2010-11-19 02:09:15

+0

字典? – 2010-11-19 02:11:50

回答

6

既然你已经表明你没有使用.NET 4,你必须定义一个类或结构保持两个字符串你有兴趣:

class Foo 
{ 
    public StringOne { get; set; } 
    public StringTwo { get; set; } 
} 

然后用Dictionary<string, Foo>,像这样:

var dict = new Dictionary<string, Foo>(); 
dict["key"] = new Foo() { 
    StringOne = "Hello", 
    StringTwo = "World" 
}; 

不要忘记给这个类及其属性一些有意义的名字。

+0

不使用.net 4.0。找到一个名为keyValuedPair的类。 – user496949 2010-11-19 02:24:00

+2

KeyValuePair不是你想要的;它旨在用于将键映射到值的字典和其他东西。请参阅我的更新的答案,这将与C#3和.NET 2.0/3.5一起使用。 – cdhowie 2010-11-19 02:24:38

+0

看起来像只是对,有什么区别? – user496949 2010-11-19 02:28:36

3

为什么不写这个

class StringPair { 
    public string Item1 { get; set; } 
    public string Item2 { get; set; } 
} 

Dictionary<TKey, StringPair> 
+0

不喜欢这个简单任务的额外课程 – user496949 2010-11-19 02:25:58

+0

你没有什么可以做的。抱歉。 – 2010-11-19 02:26:24

+0

元组真的好多了。不幸的是,它仅在4.0版本中是 – user496949 2010-11-19 02:26:40

1

将这项工作吗?

class Table<TKey, TValues> 
{ 
    Dictionary<TKey, int> lookup; 
    List<TValues[]> array; 

    public Table() 
    { 
     this.lookup = new Dictionary<TKey, int>(); 
     this.array = new List<TValues[]>(); 
    } 
    public void Add(TKey key, params TValues[] values) 
    { 
     array.Add(values); 
     lookup.Add(key, array.Count - 1); 
    } 

    public TValues[] this[TKey key] 
    { 
     get { return array[lookup[key]]; } 
     set { array[lookup[key]] = value; } 
    } 
} 

class Program 
{ 

    static void Main(string[] args) 
    { 
     Table<int, string> table = new Table<int, string>(); 
     table.Add(10001, "Joe", "Curly", "Mo"); 
     table.Add(10002, "Alpha", "Beta"); 
     table.Add(10101, "UX-300", "UX-201", "HX-100b", "UT-910"); 

     string[] parts = table[10101]; 
     // returns "UX-300", "UX-201", "HX-100b" and "UT-910". 
    } 
}