返回多个值 [英] Return more than one value

查看:65
本文介绍了返回多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

是否有可能从另一个类返回多个值,例如我有一个方法:

Hi all,

Is it possible to return more than 1 value from another class for example I have a method:

Public Shared Function GetCustomerData() as Boolean
Dim strMsg as String
Dim i as Integer

If txtNumber1.Text <> String.Empty AND txtNumber2.Text <> String.Empty Then
   i = txtNumber1.Text + txtNumber2.Text
Else
   strMsg="Requirement is empty"
End If

Return i
End Function




这是我的代码示例,我将该代码称为其他类中的函数方法,并希望返回2值,即"i"和"strMsg"

有人可以帮我解决这个问题吗?我尝试过"Return i,strMsg",但是它带有蓝色下划线字符串




This is an example of my code which I call the function method located in other class and want to return a 2 value that is "i" and "strMsg"

Could someone help me solve this? I''ve tried "Return i, strMsg" but it got blue underline string

推荐答案

创建一个结构以保存返回数据,然后填充该结构的实例并返回该值.
Create a structure to hold the return data, then populate an instance of the structure and return that.


没有诸如从类中返回值"之类的概念,它可能几乎意味着任何东西.您只能从函数返回值.

有两种方法.

第一种方法是使用封装两个或多个值的数据类型.它可以是类或结构.

第二种方法是使用out参数. VB.NET中未实现此功能,但是您可以通过引用使用传递参数,如本示例所示:
There is no such concept as "return a value from class", simply it can mean just about anything. You can return a value only from a function.

There are two ways of doing that.

Fist one is using a data type encapsulating two or more values. It could be a class or a structure.

The second way is using out parameter. This feature is not implemented in VB.NET, but you can use passing parameters by reference, like in this example:
Private Function GetCustomerData(ByRef index As Integer, ByRef message As String) As Boolean
    index = 13
    message = "message"
    Return True
End Function



在此示例中,您将返回三种不同类型的三个不同参数.布尔参数在堆栈上返回,另外两个则通过函数中传递的引用就地填充".

—SA



In this sample, you return three different parameters of three different type. The Boolean parameters is returned on stack, and the other two are "populated in-place" by the references passed in the function.

—SA


SAKryukov 在解决方案2中和 Dave Kreskowiak 在解决方案1中给出的是绝对正确的答案.
我想补充一点,在.NET FrameWork 4及更高版本中,提供了一个Tuple类,以轻松创建具有多个成员的数据结构,如此处所述
关于MSDN上的元组类 [
What is given in Solution 2 by SAKryukov and in Solution 1 by Dave Kreskowiak is absolutely correct answer.
I want to add that in .NET FrameWork 4 and above a Tuple class is provided to readily create a data structure with multiple members as explained here
About Tuple Class on MSDN[^]


这篇关于返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆