C ++ std :: pair의 C # 아날로그 란 무엇입니까?
관심이 있습니다 : std::pair
C ++에서 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에서 내부 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 월 업데이트 : Tuples
버전 4.0 이후 .NET에 포함되었습니다.
다음은 .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 <TKey, TValue>를 찾고 있습니다.
달성하고자하는 것에 따라 KeyValuePair 를 사용해 볼 수 있습니다 .
항목의 키를 변경할 수 없다는 사실은 전체 항목을 새로운 KeyValuePair 인스턴스로 간단히 바꾸어 수정할 수 있습니다.
나는 Tuples의 C # 구현을 만들었습니다. 이는 일반적으로 2에서 5 사이의 값에 대한 문제를 해결합니다. 여기 소스에 대한 링크가 포함 된 블로그 게시물 이 있습니다.
나는 빠른 구글 후에 바로 같은 질문을하고 있었다 .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 라이브러리 (이전의 Wintellect에서 사용 가능했지만 현재 Codeplex @ http://powercollections.codeplex.com 에서 호스팅 됨 )에는 일반적인 쌍 구조가 있습니다.
커스텀 클래스 또는 .Net 4.0 Tuple과는 별도로 C # 7.0 이후에는 ValueTuple이라는 새로운 기능이 있는데,이 경우이 기능을 사용할 수 있습니다. 글을 쓰는 대신 :
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);
참고 URL : https://stackoverflow.com/questions/166089/what-is-c-sharp-analog-of-c-stdpair
'Programing' 카테고리의 다른 글
Sublime Text 3의 프로젝트에서 모든 파일 검색 (0) | 2020.03.27 |
---|---|
C #에 HashSet에 해당하는 AddRange가 있습니까? (0) | 2020.03.27 |
개발을위한 장치 설정 (???????????? 권한 없음) (0) | 2020.03.26 |
PDOException SQLSTATE [HY000] [2002] 해당 파일 또는 디렉토리가 없음 (0) | 2020.03.26 |
일반 JavaScript를 사용한 "hasClass"기능은 무엇입니까? (0) | 2020.03.26 |