是否有一种方法可以使用Tuple类,但在其中提供项目的名称?

例如:

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

它返回OrderGroupId、OrderTypeId、OrderSubTypeId和OrderRequirementId的id。

让我的方法的用户知道哪个是哪个就好了。(当您调用该方法时,结果为result。Item1,结果。第二条,结果。Item3 result.Item4。不清楚哪个是哪个。)

(我知道我可以创建一个类来保存所有这些id,但这些id已经有自己的类,它们生活在其中,为这个方法的返回值创建一个类似乎很愚蠢。)


当前回答

在。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# 7.0 (Visual Studio 2017)中,有一个新的结构可以做到这一点:

(string first, string middle, string last) LookupName(long id)
(double, int) t1 = (4.5, 3);
Console.WriteLine($"Tuple with elements {t1.Item1} and {t1.Item2}.");
// Output:
// Tuple with elements 4.5 and 3.

(double Sum, int Count) t2 = (4.5, 3);
Console.WriteLine($"Sum of {t2.Count} elements is {t2.Sum}.");
// Output:
// Sum of 3 elements is 4.5.

来自Docs: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples

直到c# 7.0,除了定义自己的类型,还没有办法做到这一点。

为什么不使用多个返回而不是使用元组

var handler = GenerateFromMethod1(hits);
Process(handler.string1, handler.string1);

private static (string string1, string string2) GenerateFromMethod1()
{

}

这是非常烦人的,我希望未来的c#版本能够解决这一需求。我发现最简单的方法是使用不同的数据结构类型,或者重命名“items”,以使您和其他阅读您的代码的人能够正常阅读。

Tuple<ApiResource, JSendResponseStatus> result = await SendApiRequest();
ApiResource apiResource = result.Item1;
JSendResponseStatus jSendStatus = result.Item2;