developer tip

향후 버전의 .NET은 C #에서 튜플을 지원합니까?

optionbox 2020. 11. 3. 07:57
반응형

향후 버전의 .NET은 C #에서 튜플을 지원합니까?


.Net 3.5는 튜플을 지원하지 않습니다. 안타깝지만 .net의 향후 버전이 튜플을 지원할지 여부가 확실하지 않습니까?


MSDN Magazine : Building Tuple 에서이 기사를 읽었습니다.

다음은 발췌 내용입니다.

곧 출시 될 Microsoft .NET Framework 4.0 릴리스에는 System.Tuple이라는 새로운 유형이 도입되었습니다. System.Tuple은 유형이 다른 데이터의 고정 크기 컬렉션입니다.    

 

배열과 마찬가지로 튜플은 일단 생성되면 변경할 수없는 고정 된 크기를 갖습니다. 배열과 달리 튜플의 각 요소는 다른 유형일 수 있으며 튜플은 각 요소에 대해 강력한 유형을 보장 할 수 있습니다.

 

System.Collections.Generic 네임 스페이스 인 KeyValuePair에는 Microsoft .NET Framework 주변에 떠있는 튜플의 예가 이미 있습니다. KeyValuePair는 Tuple과 동일하다고 생각할 수 있지만 두 가지 유형이 모두 포함되어 있기 때문에 KeyValuePair는 저장하는 두 값 사이의 관계를 불러 일으키기 때문에 Tuple과 다른 느낌을줍니다 (그리고 Dictionary 클래스를 지원하기 때문에 좋은 이유가 있습니다). ).

또한 튜플의 크기는 임의로 지정할 수 있지만 KeyValuePair는 키와 값의 두 가지만 보유합니다.


F #과 같은 일부 언어에는 튜플에 대한 특수 구문이 있지만 모든 언어에서 새로운 공통 튜플 유형을 사용할 수 있습니다. 첫 번째 예제를 다시 살펴보면 유용하지만 튜플 구문이없는 언어에서는 튜플이 지나치게 장황 할 수 있음을 알 수 있습니다.

class Program {
    static void Main(string[] args) {
        Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
        PrintStringAndInt(t.Item1, t.Item2);
    }
    static void PrintStringAndInt(string s, int i) {
        Console.WriteLine("{0} {1}", s, i);
    }
}

C # 3.0의 var 키워드를 사용하면 튜플 변수에서 형식 서명을 제거 할 수 있으므로 코드를 좀 더 쉽게 읽을 수 있습니다.

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

또한 정적 튜플 클래스에 몇 가지 팩토리 메서드를 추가하여 C #과 같은 형식 유추를 지원하는 언어로 튜플을 쉽게 빌드 할 수 있습니다.

var t = Tuple.Create("Hello", 4);

#region tuples

    public class Tuple<T>
    {
        public Tuple(T first)
        {
            First = first;
        }

        public T First { get; set; }
    }

    public class Tuple<T, T2> : Tuple<T>
    {
        public Tuple(T first, T2 second)
            : base(first)
        {
            Second = second;
        }

        public T2 Second { get; set; }
    }

    public class Tuple<T, T2, T3> : Tuple<T, T2>
    {
        public Tuple(T first, T2 second, T3 third)
            : base(first, second)
        {
            Third = third;
        }

        public T3 Third { get; set; }
    }

    public class Tuple<T, T2, T3, T4> : Tuple<T, T2, T3>
    {
        public Tuple(T first, T2 second, T3 third, T4 fourth)
            : base(first, second, third)
        {
            Fourth = fourth;
        }

        public T4 Fourth { get; set; }
    }

    #endregion

그리고 선언을 더 예쁘게 만들려면 :

public static class Tuple
{
    //Allows Tuple.New(1, "2") instead of new Tuple<int, string>(1, "2")
    public static Tuple<T1, T2> New<T1, T2>(T1 t1, T2 t2)
    {
        return new Tuple<T1, T2>(t1, t2);
    }
    //etc...
}

Lokad 공유 라이브러리 (물론 오픈 소스)에는 다음과 같은 필수 기능이 포함 적절한 (빠르지 않은) C # 튜플 구현이 있습니다.

  • 2-5 개의 불변 튜플 구현
  • 적절한 DebuggerDisplayAttribute
  • 적절한 해싱 및 동등성 검사
  • 제공된 매개 변수 (제네릭은 컴파일러에서 유추 됨)에서 튜플을 생성하기위한 도우미 및 컬렉션 기반 작업을위한 확장입니다.
  • 생산 테스트를 거쳤습니다.

Implementing Tuple classes or reusing F# classes within C# is only half the story - these give you the ability to create tuples with relative ease, but not really the syntactic sugar which makes them so nice to use in languages like F#.

For example in F# you can use pattern matching to extract both parts of a tuple within a let statment, eg

let (a, b) = someTupleFunc

Unfortunately to do the same using the F# classes from C# would be much less elegant:

Tuple<int,int> x = someTupleFunc();
int a = x.get_Item1();
int b = x.get_Item2();

Tuples represent a powerful method for returning multiple values from a function call without the need to litter your code with throwaway classes, or resorting to ugly ref or out parameters. However, in my opinion, without some syntactic sugar to make their creation and access more elegant, they are of limited use.


In my opinion, the anonymous types feature is not a tuple, but a very similar construct. The output of some LINQ Queries are collections of anonymous types, which behave like tuples.

Here is a statement, which creates a typed tuple :-) on the fly:

var p1 = new {a = "A", b = 3};

see: http://www.developer.com/net/csharp/article.php/3589916


C# 7 supports tuples natively:

var unnamedTuple = ("Peter", 29);
var namedTuple = (Name: "Peter", Age: 29);
(string Name, double Age) typedTuple = ("Peter", 29);

My open source .NET Sasa library has had tuples for years (along with plenty of other functionality, like full MIME parsing). I've been using it in production code for a good few years now.


C# supports simple tuples via generics quite easily (as per an earlier answer), and with "mumble typing" (one of many possible C# language enhancements) to improve type inference they could be very, very powerful.

For what it is worth, F# supports tuples natively, and having played with it, I'm not sure that (anonymous) tuples add much... what you gain in brevity you lose very quickly in code clarity.

For code within a single method, there are anonymous types; for code going outside of a method, I think I'll stick to simple named types. Of course, if a future C# makes it easier to make these immutable (while still easy to work with) I'll be happy.


Here's my set of tuples, they're autogenerated by a Python script, so I've perhaps gone a bit overboard:

Link to Subversion repository

You'll need a username/password, they're both guest

They are based on inheritance, but Tuple<Int32,String> will not compare equal to Tuple<Int32,String,Boolean> even if they happen to have the same values for the two first members.

They also implement GetHashCode and ToString and so forth, and lots of smallish helper methods.

Example of usage:

Tuple<Int32, String> t1 = new Tuple<Int32, String>(10, "a");
Tuple<Int32, String, Boolean> t2 = new Tuple<Int32, String, Boolean>(10, "a", true);
if (t1.Equals(t2))
    Console.Out.WriteLine(t1 + " == " + t2);
else
    Console.Out.WriteLine(t1 + " != " + t2);

Will output:

10, a != 10, a, True

If I remember my Computer Science classes correctly tuples are just data.

If you want grouped data - create classes that contain properties. If you need something like the KeyValuePair then there it is.


I'd be surprised - C# is a strongly-typed language, whereas tuples are suited for more dynamically typed languages. C# has been drifting more dynamic as time goes on, but that's syntactic sugar, not a real shift in the underlying data types.

If you want two values in one instance, a KeyValuePair<> is a decent substitute, albeit clumsy. You can also make a struct or a class that'll do the same thing, and is expandable.


To make these useful in a hashtable or dictionary, you will likely want to provide overloads for GetHashCode and Equals.

참고URL : https://stackoverflow.com/questions/152019/will-a-future-version-of-net-support-tuples-in-c

반응형