gpt4 book ai didi

c# - 在 C# 中内联使用返回多个值的函数

转载 作者:行者123 更新时间:2023-11-30 14:57:49 24 4
gpt4 key购买 nike

我习惯于使用像这样“内联”返回单个值的函数:

Label1.Text = firstString + functionReturnSecondString(aGivenParameter);

对于返回两个值的函数可以这样做吗?
假设示例:

label1.Text = multipleReturnFunction(parameter).firstValue

我一直在研究返回多个值,看起来最好的选择是使用元组、结构或数组列表。

我制作了一个可以重新调整结构的工作函数。但是,我需要先调用该函数,然后才能使用这些值。如果不编写另一个函数,似乎不可能让它全部发生在同一行上。

multipleReturnFunction(parameter);
Label1.Text = firstString + classOfStruct.secondString;

我还没有制作返回元组或数组列表的函数,所以我不确定。是否可以调用这些函数并“内联”引用返回值?

感谢您的反馈。

最佳答案

对于这种情况,我有一个很糟糕的 hack - 当你想对返回值执行多个操作而不定义一个额外的变量来存储它时:

public static TResult Apply<TInput, TResult>(this TInput input, Func<TInput, TResult> transformation)
{
return transformation(input);
}

...这就是它最初出现的原因:

var collection = Enumerable.Range(1, 3);

// Average reimplemented with Aggregate.
double average = collection
.Aggregate(
new { Count = 0, Sum = 0 },
(acc, i) => new { Count = acc.Count + 1, Sum = acc.Sum + i })
.Apply(a => (double)a.Sum / (double)a.Count); // Note: we have access to both Sum and Count despite never having stored the result of the call to .Aggregate().

Console.WriteLine("Average: {0}", average);

不用说,这比实际的生产代码更适合学术练习。

关于c# - 在 C# 中内联使用返回多个值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20163141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com