我感兴趣的是:c++中类似std::pair的c#是什么?我找到System.Web.UI.Pair类,但我更喜欢基于模板的东西。
谢谢你!
我感兴趣的是:c++中类似std::pair的c#是什么?我找到System.Web.UI.Pair类,但我更喜欢基于模板的东西。
谢谢你!
当前回答
ui包含Pair类,因为它在ASP中被大量使用。NET 1.1作为内部ViewState结构。
2017年8月更新:c# 7.0 / . net Framework 4.7提供了一种语法,可以使用System声明具有命名项的元组。ValueTuple结构。
//explicit Item typing
(string Message, int SomeNumber) t = ("Hello", 4);
//or using implicit typing
var t = (Message:"Hello", SomeNumber:4);
Console.WriteLine("{0} {1}", t.Message, t.SomeNumber);
更多语法示例请参见MSDN。
2012年6月更新:元组从4.0版开始就成为。net的一部分。
以下是之前的一篇文章,描述了包含in.NET4.0和对泛型的支持:
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
其他回答
我创建了一个元组的c#实现,它一般解决2到5个值之间的问题-这里是博客文章,其中包含一个到源代码的链接。
不幸的是,没有。你可以使用System.Collections.Generic。KeyValuePair<K, V>在许多情况下。
或者,你可以使用匿名类型来处理元组,至少在本地:
var x = new { First = "x", Second = 42 };
最后一种选择是创建自己的类。
PowerCollections库(以前可从Wintellect获得,但现在托管在Codeplex @ http://powercollections.codeplex.com上)具有通用的Pair结构。
如果是关于字典之类的,你要找System.Collections.Generic。KeyValuePair < TKey, TValue >。
我通常将Tuple类扩展到我自己的泛型包装器中,如下所示:
public class Statistic<T> : Tuple<string, T>
{
public Statistic(string name, T value) : base(name, value) { }
public string Name { get { return this.Item1; } }
public T Value { get { return this.Item2; } }
}
像这样使用它:
public class StatSummary{
public Statistic<double> NetProfit { get; set; }
public Statistic<int> NumberOfTrades { get; set; }
public StatSummary(double totalNetProfit, int numberOfTrades)
{
this.TotalNetProfit = new Statistic<double>("Total Net Profit", totalNetProfit);
this.NumberOfTrades = new Statistic<int>("Number of Trades", numberOfTrades);
}
}
StatSummary summary = new StatSummary(750.50, 30);
Console.WriteLine("Name: " + summary.NetProfit.Name + " Value: " + summary.NetProfit.Value);
Console.WriteLine("Name: " + summary.NumberOfTrades.Value + " Value: " + summary.NumberOfTrades.Value);