Jon*_*eet 62
只需创建一个Pair<TFirst, TSecond>
类型并将其用作您的值.
我在我的C#深度源代码中有一个例子.为简单起见,这里转载:
using System;
using System.Collections.Generic;
public sealed class Pair<TFirst, TSecond>
: IEquatable<Pair<TFirst, TSecond>>
{
private readonly TFirst first;
private readonly TSecond second;
public Pair(TFirst first, TSecond second)
{
this.first = first;
this.second = second;
}
public TFirst First
{
get { return first; }
}
public TSecond Second
{
get { return second; }
}
public bool Equals(Pair<TFirst, TSecond> other)
{
if (other == null)
{
return false;
}
return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&
EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
}
public override bool Equals(object o)
{
return Equals(o as Pair<TFirst, TSecond>);
}
public override int GetHashCode()
{
return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
EqualityComparer<TSecond>.Default.GetHashCode(second);
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*son 58
如果您尝试将值组合在一起,这可能是创建简单结构或类并将其用作字典中的值的绝佳机会.
public struct MyValue
{
public object Value1;
public double Value2;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以有你的字典
var dict = new Dictionary<int, MyValue>();
Run Code Online (Sandbox Code Playgroud)
你甚至可以更进一步实现自己的字典类,它将处理你需要的任何特殊操作.例如,如果您想要一个接受int,object和double的Add方法
public class MyDictionary : Dictionary<int, MyValue>
{
public void Add(int key, object value1, double value2)
{
MyValue val;
val.Value1 = value1;
val.Value2 = value2;
this.Add(key, val);
}
}
Run Code Online (Sandbox Code Playgroud)
那么你可以像这样简单地实例化并添加到字典中,你不必担心创建'MyValue'结构:
var dict = new MyDictionary();
dict.Add(1, new Object(), 2.22);
Run Code Online (Sandbox Code Playgroud)
tee*_*yay 26
Dictionary<T1, Tuple<T2, T3>>
Run Code Online (Sandbox Code Playgroud)
编辑:对不起 - 我忘了在.NET 4.0出来之前你没有得到Tuples.D'哦!
我认为这对于字典语义来说是相当过分的,因为字典按照定义是一组键及其各自的值,就像我们看到一本包含单词作为键的语言字典书及其描述性意义的方式一样.值.
但是您可以表示可以包含值集合的字典,例如:
Dictionary<String,List<Customer>>
Run Code Online (Sandbox Code Playgroud)
或者键的字典和作为字典的值:
Dictionary<Customer,Dictionary<Order,OrderDetail>>
Run Code Online (Sandbox Code Playgroud)
然后你将拥有一个可以有多个值的字典.
我认为您不能直接这样做。您可以创建一个同时包含object
和的类,double
然后将其实例放入字典中。
class Pair
{
object obj;
double dbl;
}
Dictionary<int, Pair> = new Dictionary<int, Pair>();
Run Code Online (Sandbox Code Playgroud)