Max*_*kin 20 c# generics tuples data-structures
也就是说,我想要一个价值元组.
我心中的用例:
Dictionary<Pair<string, int>, object>
Run Code Online (Sandbox Code Playgroud)
要么
Dictionary<Triple<string, int, int>, object>
Run Code Online (Sandbox Code Playgroud)
是否有内置类型,如Pair或Triple?或者实施它的最佳方式是什么?
更新答案中描述了一些通用元组实现,但对于在字典中用作键的元组,您应该另外验证哈希码的正确计算.在另一个问题中有关于此的更多信息.
更新2我想还值得提醒的是,当你在字典中使用某个值作为键时,它应该是不可变的.
Max*_*lle 20
在某些特定情况下,.net框架已经提供了类似元组的类,您可以利用它们.
对和三人组
通用的 System.Collections.Generic.KeyValuePair 类可以用作adhoc对实现.这是泛型Dictionary在内部使用的类.
或者,您可以使用System.Collections.DictionaryEntry 结构,该 结构充当基本对,并具有在mscorlib中可用的优势.然而,不利的是,这种结构不是强类型的.
还可以以System.Web.UI.Pair和 System.Web.UI.Triplet类的形式提供Pairs和Triple .尽管这些类存在于System.Web程序集中,但它们可能非常适合winforms开发.但是,这些类也不是强类型的,也可能不适用于某些场景,例如通用框架或库.
更高阶的元组
对于更高阶的元组,如果没有滚动自己的类,可能没有一个简单的解决方案.
如果已安装 F#语言,则可以引用包含一组通用不可变Microsoft.Fsharp.Core.Tuple类的FSharp.Core.dll, 直到通用的六进制文件.但是,即使 可以重新分发未修改的FSharp.Code.dll,F#也是一种研究语言并且正在进行中,因此这种解决方案可能只对学术界有用.
如果你不想创建自己的类并且引用F#库感到不舒服,那么一个很好的技巧可能在于扩展通用KeyValuePair类,以便Value成员本身就是嵌套的KeyValuePair.
例如,以下代码说明了如何利用KeyValuePair创建Triples:
int id = 33;
string description = "This is a custom solution";
DateTime created = DateTime.Now;
KeyValuePair<int, KeyValuePair<string, DateTime>> triple =
new KeyValuePair<int, KeyValuePair<string, DateTime>>();
triple.Key = id;
triple.Value.Key = description;
triple.Value.Value = created;
Run Code Online (Sandbox Code Playgroud)
这允许根据需要将类扩展到任意级别.
KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string>, string> quadruple =
new KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string>, string>();
KeyValuePair<KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string>, string>, string> quintuple =
new KeyValuePair<KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string>, string>, string>();
Run Code Online (Sandbox Code Playgroud)
在其他情况下,您可能需要使用滚动自己的元组类,这并不难.
您可以创建简单的结构,如下所示:
struct Pair<T, R>
{
private T first_;
private R second_;
public T First
{
get { return first_; }
set { first_ = value; }
}
public R Second
{
get { return second_; }
set { second_ = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
之前已经解决了这个问题,并且确实存在通用框架.以下是一个这样的框架的链接:
Tim*_*ter 12
public struct Pair<T1, T2>
{
public T1 First;
public T2 Second;
}
public struct Triple<T1, T2, T3>
{
public T1 First;
public T2 Second;
public T3 Third;
}
Run Code Online (Sandbox Code Playgroud)
我在C#中实现了一个元组库.访问http://www.adventuresinsoftware.com/generics/并单击"元组"链接.
| 归档时间: |
|
| 查看次数: |
12659 次 |
| 最近记录: |