是否有可能为一个函数返回两个值?

编程入门 行业动态 更新时间:2024-10-27 09:46:07
本文介绍了是否有可能为一个函数返回两个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否有可能为一个函数返回两个值? 数组是可能的,如果这两个值都相同的类型,但你如何返回两个不同类型的值?

解决方案

能否函数返回2个独立的价值观?不,在C#中的函数只能返回一个值。

有可能的,虽然使用其他概念返回2的值。 T1,T2>

<$ P $想到的是使用包装类型,例如元组LT第一p> 元组LT; INT,串>的GetValues​​(){返回Tuple.Create(42,富); }

元组LT; T1,T2> 类型仅在4.0和更高版本可用。如果您使用的是框架的早期版本,你可以创建自己的类型或使用 KeyValuePair< TKEY的,TValue方式>

KeyValuePair< INT,串>的GetValues​​(){返回新KeyValuePair< INT,刺痛>(42,富); }

另一种方法是使用一个输出参数(我会强烈建议更换元组方式。虽然)

INT的GetValues​​(字符串进行参数1){参数1 =富; 返回42; }

Is it possible for a function to return two values? Array is possible if the two values are both the same type, but how do you return two different type values?

解决方案

Can a function return 2 separate values? No, a function in C# can only return a single value.

It is possible though to use other concepts to return 2 values. The first that comes to mind is using a wrapping type such as a Tuple<T1,T2>.

Tuple<int,string> GetValues() { return Tuple.Create(42,"foo"); }

The Tuple<T1,T2> type is only available in 4.0 and higher. If you are using an earlier version of the framework you can either create your own type or use KeyValuePair<TKey,TValue>.

KeyValuePair<int,string> GetValues() { return new KeyValuePair<int,sting>(42,"foo"); }

Another method is to use an out parameter (I would highly recomend the tuple approach though).

int GetValues(out string param1) { param1 = "foo"; return 42; }

更多推荐

是否有可能为一个函数返回两个值?

本文发布于:2023-06-08 03:50:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/576124.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有可能   两个   一个函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!