[C#] C ++ std :: pair의 C # 아날로그 란 무엇입니까?

관심이 있습니다 : std::pairC ++에서 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.UIPairASP.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부터 튜플이 있습니다.


답변

일부 답변은 잘못 된 것 같습니다.

  1. 쌍 (a, b)와 (a, c)를 저장하는 방법을 사전으로 사용할 수 없습니다. 쌍 개념을 키와 값의 연관 조회와 혼동해서는 안됩니다.
  2. 위의 코드 중 상당수가 의심스러운 것 같습니다.

여기 내 페어 클래스입니다

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 인스턴스로 간단히 바꾸어 수정할 수 있습니다.