本文介绍了什么是C#std :: pair的C#模拟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感兴趣的是什么是C#std :: pair的C#模拟?我找到了System.Web.UI.Pair类,但是想要一些基于模板的。



谢谢!

解决方案

元组可用,并支持泛型:

 元组< string,int> t = new Tuple< string,int>(Hello,4); 






在以前的版本中,您可以使用 System.Collections.Generic.KeyValuePair< K,V> 或解决方案如下:

 公共类对< T,U> {
public Pair(){
}

public Pair(T first,U second){
this.First = first;
this.Second = second;
}

public T First {get;组; }
public U Second {get;组; }
};

使用如下:

  Pair< String,int> pair = new Pair< String,int>(test,2); 
Console.WriteLine(pair.First);
Console.WriteLine(pair.Second);

输出:

  test 
2

甚至这个链接对:

  Pair< Pair< String,int>,bool> pair = new Pair< Pair< String,int>,bool>(); 
pair.First = new Pair< String,int>();
pair.First.First =test;
pair.First.Second = 12;
pair.Second = true;

Console.WriteLine(pair.First.First);
Console.WriteLine(pair.First.Second);
Console.WriteLine(pair.Second);

输出:

  test 
12
true


I am interested what is C# analog of C++ std::pair? I have found System.Web.UI.Pair class, but wanted something template based.

Thank you!

解决方案

Tuples are available since .NET4.0 and support generics:

Tuple<string, int> t = new Tuple<string, int>("Hello", 4);


In previous versions you can use System.Collections.Generic.KeyValuePair<K, V> or a solution like the following:

public class Pair<T, U> {
    public Pair() {
    }

    public Pair(T first, U second) {
        this.First = first;
        this.Second = second;
    }

    public T First { get; set; }
    public U Second { get; set; }
};

And use it like this:

Pair<String, int> pair = new Pair<String, int>("test", 2);
Console.WriteLine(pair.First);
Console.WriteLine(pair.Second);

This outputs:

test
2

Or even this chained pairs:

Pair<Pair<String, int>, bool> pair = new Pair<Pair<String, int>, bool>();
pair.First = new Pair<String, int>();
pair.First.First = "test";
pair.First.Second = 12;
pair.Second = true;

Console.WriteLine(pair.First.First);
Console.WriteLine(pair.First.Second);
Console.WriteLine(pair.Second);

That outputs:

test
12
true

这篇关于什么是C#std :: pair的C#模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 22:09