[C#] “Item1”, “Item2″보다 Tuple 클래스에서 더 나은 이름 지정

Tuple 클래스를 사용하는 방법이 있지만 그 안에 항목의 이름을 제공합니까?

예를 들면 다음과 같습니다.

public Tuple<int, int, int int> GetOrderRelatedIds()

OrderGroupId, OrderTypeId, OrderSubTypeId 및 OrderRequirementId의 ID를 리턴합니다.

내 방법의 사용자에게 어느 것이 무엇인지 알려주는 것이 좋을 것입니다. (메소드를 호출하면 결과는 result.Item1, result.Item2, result.Item3, result.Item4입니다. 어느 것이 어느 것인지 명확하지 않습니다.)

(나는이 모든 ID를 보유 할 클래스를 만들 수 있다는 것을 알고 있지만이 ID에는 이미 자체 클래스가 있으며이 메소드의 반환 값에 대한 클래스를 만드는 것은 어리석은 것처럼 보입니다.)



답변

C # 7.0 (Visual Studio 2017)에는이를위한 새로운 구성이 있습니다.

(string first, string middle, string last) LookupName(long id)


답변

C # 7.0까지는 자체 유형을 정의하는 데 짧은 방법이 없었습니다.


답변

당신이 요구하는 것의 지나치게 복잡한 버전은 다음과 같습니다.

class MyTuple : Tuple<int, int>
{
    public MyTuple(int one, int two)
        :base(one, two)
    {

    }

    public int OrderGroupId { get{ return this.Item1; } }
    public int OrderTypeId { get{ return this.Item2; } }

}

왜 수업을하지 않습니까?


답변

.net 4를 사용하면 아마도을 볼 수 ExpandoObject는 있지만 컴파일 타임 오류가 런타임 오류가 된 것처럼 간단한 경우에는 사용하지 마십시오.

class Program
{
    static void Main(string[] args)
    {
        dynamic employee, manager;

        employee = new ExpandoObject();
        employee.Name = "John Smith";
        employee.Age = 33;

        manager = new ExpandoObject();
        manager.Name = "Allison Brown";
        manager.Age = 42;
        manager.TeamSize = 10;

        WritePerson(manager);
        WritePerson(employee);
    }
    private static void WritePerson(dynamic person)
    {
        Console.WriteLine("{0} is {1} years old.",
                          person.Name, person.Age);
        // The following statement causes an exception
        // if you pass the employee object.
        // Console.WriteLine("Manages {0} people", person.TeamSize);
    }
}
// This code example produces the following output:
// John Smith is 33 years old.
// Allison Brown is 42 years old.

언급할만한 가치가있는 것은 메소드 내에서 익명 유형 이지만 클래스를 반환하려면 클래스를 만들어야합니다.

var MyStuff = new
    {
        PropertyName1 = 10,
        PropertyName2 = "string data",
        PropertyName3 = new ComplexType()
    };


답변

게시물에 더 적합하기 때문에이 게시물 에서 내 대답을 재현 합니다.

C # v7.0부터는 이전 Item1Item2와 같이 사전 정의 된 이름을 기본값으로 사용했던 튜플 특성의 이름을 지정할 수 있습니다.

튜플 리터럴의 속성 이름 지정 :

var myDetails = (MyName: "RBT_Yoga", MyAge: 22, MyFavoriteFood: "Dosa");
Console.WriteLine($"Name - {myDetails.MyName}, Age - {myDetails.MyAge}, Passion - {myDetails.MyFavoriteFood}");

콘솔의 출력 :

이름-RBT_Yoga, 나이-22, 열정-Dosa

메소드에서 Tuple 반환 (명명 된 속성이 있음) :

static void Main(string[] args)
{
    var empInfo = GetEmpInfo();
    Console.WriteLine($"Employee Details: {empInfo.firstName}, {empInfo.lastName}, {empInfo.computerName}, {empInfo.Salary}");
}

static (string firstName, string lastName, string computerName, int Salary) GetEmpInfo()
{
    //This is hardcoded just for the demonstration. Ideally this data might be coming from some DB or web service call
    return ("Rasik", "Bihari", "Rasik-PC", 1000);
}

콘솔의 출력 :

직원 세부 정보 : Rasik, Bihari, Rasik-PC, 1000

명명 된 속성을 가진 튜플 목록 만들기

var tupleList = new List<(int Index, string Name)>
{
    (1, "cow"),
    (5, "chickens"),
    (1, "airplane")
};

foreach (var tuple in tupleList)
    Console.WriteLine($"{tuple.Index} - {tuple.Name}");

콘솔 출력 :

1-소 5-닭 1-비행기

나는 모든 것을 다뤘기를 바랍니다. 내가 놓친 것이 있으면 의견에 의견을 보내주십시오.

참고 : 내 코드 스 니펫은 여기에 자세히 설명 된대로 C # v7의 문자열 보간 기능을 사용하고 있습니다 .


답변

MichaelMocko Answered는 훌륭합니다.

하지만 알아 내야 할 몇 가지를 추가하고 싶습니다

(string first, string middle, string last) LookupName(long id)

위의 줄은 .net 프레임 워크 <4.7을 사용하는 경우 컴파일 시간 오류를 발생시킵니다

따라서 .net 프레임 워크 <4.7을 사용하는 프로젝트가 있고 여전히 workTuround보다 ValueTuple을 사용하려는 경우이 nuget 패키지를 설치 합니다


답변

아니요, 튜플 멤버의 이름을 지정할 수 없습니다.

그 사이는 Tuple 대신 ExpandoObject 를 사용 하는 것입니다.