무엇 C#아날로그의 C++std::pair?
-
03-07-2019 - |
문제
내가 관심있:무엇 C#'s 의 아날로그 std::pair
에서는 C++?내가 발견 System.Web.UI.Pair
클래스,하지만 난 뭔가 선호 템플릿을 기반으로 합니다.
감사합니다!
해결책
튜플 .NET4.0 이후로 사용할 수 있습니다 제네릭 지원 :
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
이전 버전에서 사용할 수 있습니다 System.Collections.Generic.KeyValuePair<K, V>
또는 다음과 같은 솔루션 :
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; }
};
다음과 같이 사용하십시오.
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
다른 팁
System.Web.UI
포함 Pair
클래스는 ASP.NET 1.1에서 내부 뷰 스테이트 구조로 많이 사용 되었기 때문에 클래스.
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 월 업데이트 : Tuples
버전 4.0 이후 .NET의 일부였습니다.
여기에 있습니다 Inclusion in.net4.0을 설명하는 이전 기사 제네릭에 대한 지원 :
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
불행하게도,가 존재하지 않는다는 사실입니다.사용할 수 있습니다 System.Collections.Generic.KeyValuePair<K, V>
상황이 많습니다.
또는,사용할 수 있는 익명 형식을 처리 지어,적어도 로컬로:
var x = new { First = "x", Second = 42 };
마지막 대안을 만드는 것이 자신의 클래스입니다.
C#가 있습니다 튜플 버전 4.0 기준.
일부 답변은 틀린 것 같습니다.
- 사전 (a, b) 및 (a, c)를 저장하는 방법을 사용할 수 없습니다. 쌍 개념은 키와 가치의 연관 조회와 혼동되어서는 안됩니다.
- 위의 코드의 많은 부분은 용의자로 보입니다
여기 내 쌍 수업이 있습니다
public class Pair<X, Y>
{
private X _x;
private Y _y;
public Pair(X first, Y second)
{
_x = first;
_y = second;
}
public X first { get { return _x; } }
public Y second { get { return _y; } }
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj == this)
return true;
Pair<X, Y> other = obj as Pair<X, Y>;
if (other == null)
return false;
return
(((first == null) && (other.first == null))
|| ((first != null) && first.Equals(other.first)))
&&
(((second == null) && (other.second == null))
|| ((second != null) && second.Equals(other.second)));
}
public override int GetHashCode()
{
int hashcode = 0;
if (first != null)
hashcode += first.GetHashCode();
if (second != null)
hashcode += second.GetHashCode();
return hashcode;
}
}
다음은 몇 가지 테스트 코드입니다.
[TestClass]
public class PairTest
{
[TestMethod]
public void pairTest()
{
string s = "abc";
Pair<int, string> foo = new Pair<int, string>(10, s);
Pair<int, string> bar = new Pair<int, string>(10, s);
Pair<int, string> qux = new Pair<int, string>(20, s);
Pair<int, int> aaa = new Pair<int, int>(10, 20);
Assert.IsTrue(10 == foo.first);
Assert.AreEqual(s, foo.second);
Assert.AreEqual(foo, bar);
Assert.IsTrue(foo.GetHashCode() == bar.GetHashCode());
Assert.IsFalse(foo.Equals(qux));
Assert.IsFalse(foo.Equals(null));
Assert.IsFalse(foo.Equals(aaa));
Pair<string, string> s1 = new Pair<string, string>("a", "b");
Pair<string, string> s2 = new Pair<string, string>(null, "b");
Pair<string, string> s3 = new Pair<string, string>("a", null);
Pair<string, string> s4 = new Pair<string, string>(null, null);
Assert.IsFalse(s1.Equals(s2));
Assert.IsFalse(s1.Equals(s3));
Assert.IsFalse(s1.Equals(s4));
Assert.IsFalse(s2.Equals(s1));
Assert.IsFalse(s3.Equals(s1));
Assert.IsFalse(s2.Equals(s3));
Assert.IsFalse(s4.Equals(s1));
Assert.IsFalse(s1.Equals(s4));
}
}
사전 등에 관한 것이라면 System.Collections.generic.keyvaluepair를 찾고 있습니다.u003CTKey, TValue> .
성취하고자하는 것에 따라 시도해 볼 수 있습니다. keyvaluepair.
입력 키를 변경할 수 없다는 사실은 KeyValuePair의 새 인스턴스로 전체 항목을 간단히 교체하여 수정 될 수 있습니다.
튜플의 C# 구현을 만들었습니다.이 튜플은 일반적으로 2 ~ 5 값 사이의 문제를 해결합니다. 다음은 블로그 게시물입니다, 소스에 대한 링크가 포함되어 있습니다.
나는 빠른 Google 직후에 같은 질문을하고 있었는데, system.web.ui ^ ~ ^ (system.web.ui ^ ^ ^)을 제외하고 .NET에 쌍 클래스가 있음을 알았습니다.http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx) goodness는 컬렉션 프레임 워크 대신 왜 거기에 넣은 이유를 알고 있습니다.
.NET 4.0 이후로 System.Tuple<T1, T2>
수업:
// pair is implicitly typed local variable (method scope)
var pair = System.Tuple.Create("Current century", 21);
나는 일반적으로 연장됩니다 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);
위의 작업을 수행하기 위해 (사전 열쇠로 쌍이 필요했습니다). 추가해야했습니다.
public override Boolean Equals(Object o)
{
Pair<T, U> that = o as Pair<T, U>;
if (that == null)
return false;
else
return this.First.Equals(that.First) && this.Second.Equals(that.Second);
}
그리고 일단 내가 그렇게 한 후에도 추가했습니다
public override Int32 GetHashCode()
{
return First.GetHashCode() ^ Second.GetHashCode();
}
컴파일러 경고를 억제합니다.
PowerCollections Library (이전에는 WintEllect에서 제공되었지만 현재 CodePlex @에서 호스팅되었습니다. http://powercollections.codeplex.com)에는 일반 쌍 구조가 있습니다.
C# 7.0이므로 Valuetuple이라는 새로운 기능이 있기 때문에 사용자 정의 클래스 또는 .NET 4.0 튜플 외에도이 경우 사용할 수있는 구조물입니다. 글쓰기 대신 :
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
및 액세스 값을 통해 t.Item1
그리고 t.Item2
, 당신은 단순히 그것을 할 수 있습니다 :
(string message, int count) = ("Hello", 4);
또는:
(var message, var count) = ("Hello", 4);