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

例如:

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

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

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

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


当前回答

到今天为止,就是这么简单。而不是使用Tuple关键字

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

用这个。

public (int alpha, int beta, int candor) GetOrderRelatedIds()

得到这样的值。

var a = GetOrderRelatedIds();
var c = a.alpha;

其他回答

不,你不能命名元组成员。

中间的方法是使用ExpandoObject而不是Tuple。

我会把商品名称写在汇总单上。 因此,通过将鼠标悬停在helloworld()函数上,文本将显示hello = Item1和world = Item2

 helloworld("Hi1,Hi2");

/// <summary>
/// Return hello = Item1 and world Item2
/// </summary>
/// <param name="input">string to split</param>
/// <returns></returns>
private static Tuple<bool, bool> helloworld(string input)
{
    bool hello = false;
    bool world = false;
    foreach (var hw in input.Split(','))
    {
        switch (hw)
        {
            case "Hi1":
                hello= true;
                break;
            case "Hi2":
                world= true;
                break;
        }

    }
    return new Tuple<bool, bool>(hello, world);
}

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

Tuple<ApiResource, JSendResponseStatus> result = await SendApiRequest();
ApiResource apiResource = result.Item1;
JSendResponseStatus jSendStatus = result.Item2;
(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

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

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

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

}