C++ 표준::쌍의 C# 아날로그는 무엇입니까?
관심이 있습니다.C#의 유사점은 무엇입니까?std::pairC++로?찾았습니다System.Web.UI.Pair수업이요, 하지만 저는 템플릿 기반의 것을 선호합니다.
감사해요!
튜플은 이후부터 사용할 수 있습니다.NET 4.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에서 내부 ViewState 구조로 많이 사용되었기 때문입니다.
2017년 8월 업데이트: C# 7.0 / .NET Framework 4.7은 구조체를 사용하여 명명된 항목으로 Tuple을 선언하는 구문을 제공합니다.
//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의 일부가 되었습니다.
다음은 에 포함된 내용을 설명하는 이전 기사입니다.NET 4.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));
}
}
사용자 지정 클래스 또는 .Net 4.0 Tuples, C# 7.0 이후에는 ValueTuples라는 새로운 기능이 있으며, 이 경우에 사용할 수 있는 구조입니다.쓰는 대신:
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);
사전 등에 관한 것이라면 시스템을 찾는 것입니다.컬렉션.포괄적인.키 값 쌍<TKey, TValue >.
저는 Tuples의 C# 구현을 만들었습니다. 이 구현은 두 개에서 다섯 개 사이의 값으로 문제를 일반적으로 해결합니다. 여기 소스에 대한 링크가 포함된 블로그 게시물이 있습니다.
나는 일반적으로 확장합니다.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);
수행할 작업에 따라 KeyValuePair를 사용해 볼 수도 있습니다.
항목 키를 변경할 수 없다는 사실은 전체 항목을 KeyValuePair의 새 인스턴스로 바꾸기만 하면 해결할 수 있습니다.
빠른 구글 검색 후에 방금 같은 질문을 하고 있었는데 시스템에 있는 것을 제외하고 .NET에 쌍 클래스가 있다는 것을 발견했습니다.Web.UI ^ ~ ^ (http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx) 은 컬렉션 프레임워크 대신 왜 그것을 거기에 두었는지 잘 알고 있습니다.
. 4로는 .NET 4.0이 .System.Tuple<T1, T2> 명령어:
// pair is implicitly typed local variable (method scope)
var pair = System.Tuple.Create("Current century", 21);
위의 작업을 수행하기 위해서는 사전의 키로 한 쌍이 필요했습니다.추가해야 했습니다.
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 라이브러리(이전에는 Wintellect에서 사용할 수 있었지만 현재는 Codeplex @ http://powercollections.codeplex.com 에서 호스팅됨)는 일반적인 Pair 구조를 가집니다.
언급URL : https://stackoverflow.com/questions/166089/what-is-c-sharp-analog-of-c-stdpair
'programing' 카테고리의 다른 글
| Bash에서 하위 문자열 추출 (0) | 2023.05.25 |
|---|---|
| 다른 지점으로 전환하려면 어떻게 해야 합니까? (0) | 2023.05.25 |
| .NET 표준과 .NET 코어 비교 (0) | 2023.05.25 |
| Node.js에서 npm 모듈을 제거하려면 어떻게 해야 합니까? (0) | 2023.05.25 |
| "*ngIf If"를 사용하려면 어떻게 해야 합니까? (0) | 2023.05.25 |