C# 向方法调用者返回多个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/748062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return multiple values to a method caller
提问by Ash
I read the C++ version of this questionbut didn't really understand it.
Can someone please explain clearly if it can be done and how?
有人可以解释清楚是否可以完成以及如何完成?
采纳答案by Hadas
In C# 7 and above, see this answer.
在 C# 7 及更高版本中,请参阅此答案。
In previous versions, you can use .NET 4.0+'s Tuple:
在以前的版本中,您可以使用.NET 4.0+ 的 Tuple:
For Example:
例如:
public Tuple<int, int> GetMultipleValue()
{
return Tuple.Create(1,2);
}
Tuples with two values have Item1
and Item2
as properties.
具有两个值的元组具有Item1
和Item2
作为属性。
回答by Chris Doggett
If you mean returning multiple values, you can either return a class/struct containing the values you want to return, or use the "out" keyword on your parameters, like so:
如果您的意思是返回多个值,则可以返回包含要返回的值的类/结构,或者在参数上使用“out”关键字,如下所示:
public void Foo(int input, out int output1, out string output2, out string errors) {
// set out parameters inside function
}
回答by Keltex
You either return a class instanceor use outparameters. Here's an example of out parameters:
您要么返回一个类实例,要么使用out参数。以下是输出参数的示例:
void mymethod(out int param1, out int param2)
{
param1 = 10;
param2 = 20;
}
Call it like this:
像这样调用它:
int i, j;
mymethod(out i, out j);
// i will be 20 and j will be 10
回答by Samuel
You cannot do this in C#. What you can do is have a out
parameter or return your own class (or struct if you want it to be immutable).
您不能在 C# 中执行此操作。您可以做的是有一个out
参数或返回您自己的类(如果您希望它不可变,则返回结构体)。
public int GetDay(DateTime date, out string name)
{
// ...
}
使用自定义类(或结构)
public DayOfWeek GetDay(DateTime date)
{
// ...
}
public class DayOfWeek
{
public int Day { get; set; }
public string Name { get; set; }
}
回答by Jose Basilio
Classes, Structures, Collections and Arrays can contain multiple values. Output and reference parameters can also be set in a function. Return multiple values is possible in dynamic and functional languages by means of tuples, but not in C#.
类、结构、集合和数组可以包含多个值。输出和参考参数也可以在函数中设置。在动态语言和函数式语言中可以通过元组返回多个值,但在 C# 中则不然。
回答by Reed Copsey
In C# 4, you will be able to use built-in support for tuples to handle this easily.
在 C# 4 中,您将能够使用对元组的内置支持来轻松处理此问题。
In the meantime, there are two options.
与此同时,有两种选择。
First, you can use ref or out parameters to assign values to your parameters, which get passed back to the calling routine.
首先,您可以使用 ref 或 out 参数为您的参数分配值,这些值会被传递回调用例程。
This looks like:
这看起来像:
void myFunction(ref int setMe, out int youMustSetMe);
Second, you can wrap up your return values into a structure or class, and pass them back as members of that structure. KeyValuePair works well for 2 - for more than 2 you would need a custom class or struct.
其次,您可以将返回值包装到一个结构或类中,并将它们作为该结构的成员传回。KeyValuePair 适用于 2 - 超过 2 您将需要自定义类或结构。
回答by Kevin Hoffman
Previous poster is right. You cannot return multiple values from a C# method. However, you do have a couple of options:
上一张海报是对的。不能从 C# 方法返回多个值。但是,您确实有几个选择:
- Return a structure that contains multiple members
- Return an instance of a class
- Use output parameters (using the outor refkeywords)
- Use a dictionary or key-value pair as output
- 返回一个包含多个成员的结构
- 返回一个类的实例
- 使用输出参数(使用out或ref关键字)
- 使用字典或键值对作为输出
The pros and cons here are often hard to figure out. If you return a structure, make sure it's small because structs are value type and passed on the stack. If you return an instance of a class, there are some design patterns here that you might want to use to avoid causing problems - members of classes can be modified because C# passes objects by reference (you don't have ByVal like you did in VB).
这里的利弊通常很难弄清楚。如果您返回一个结构,请确保它很小,因为结构是值类型并在堆栈上传递。如果你返回一个类的实例,这里有一些你可能想要使用的设计模式来避免引起问题——类的成员可以被修改,因为 C# 通过引用传递对象(你没有像在 VB 中那样的 ByVal )。
Finally you can use output parameters but I would limit the use of this to scenarios when you only have a couple (like 3 or less) of parameters - otherwise things get ugly and hard to maintain. Also, the use of output parameters can be an inhibitor to agility because your method signature will have to change every time you need to add something to the return value whereas returning a struct or class instance you can add members without modifying the method signature.
最后,您可以使用输出参数,但是当您只有几个(例如 3 个或更少)参数时,我会将它的使用限制在场景中 - 否则事情会变得丑陋且难以维护。此外,输出参数的使用可能会阻碍敏捷性,因为每次需要向返回值添加内容时,您的方法签名都必须更改,而返回结构或类实例时,您可以在不修改方法签名的情况下添加成员。
From an architectural standpoint I would recommend against using key-value pairs or dictionaries. I find this style of coding requires "secret knowledge" in code that consumes the method. It must know ahead of time what the keys are going to be and what the values mean and if the developer working on the internal implementation changes the way the dictionary or KVP is created, it could easily create a failure cascade throughout the entire application.
从架构的角度来看,我建议不要使用键值对或字典。我发现这种编码风格需要使用该方法的代码中的“秘密知识”。它必须提前知道键将是什么以及值的含义,如果从事内部实现的开发人员更改了字典或 KVP 的创建方式,则很容易在整个应用程序中创建故障级联。
回答by dustyburwell
No, you can't return multiple values from a function in C# (for versions lower than C# 7), at least not in the way you can do it in Python.
不,您不能从 C# 中的函数返回多个值(对于低于 C# 7 的版本),至少不能像在 Python 中那样返回。
However, there are a couple alternatives:
但是,有几种选择:
You can return an array of type object with the multiple values you want in it.
您可以返回一个类型为 object 的数组,其中包含您想要的多个值。
private object[] DoSomething()
{
return new [] { 'value1', 'value2', 3 };
}
You can use out
parameters.
您可以使用out
参数。
private string DoSomething(out string outparam1, out int outparam2)
{
outparam1 = 'value2';
outparam2 = 3;
return 'value1';
}
回答by Andrew Hare
There are several ways to do this. You can use ref
parameters:
有几种方法可以做到这一点。您可以使用ref
参数:
int Foo(ref Bar bar) { }
This passes a reference to the function thereby allowing the function to modify the object in the calling code's stack. While this is not technically a "returned" value it is a way to have a function do something similar. In the code above the function would return an int
and (potentially) modify bar
.
这将传递对函数的引用,从而允许函数修改调用代码堆栈中的对象。虽然这在技术上不是“返回”值,但它是一种让函数做类似事情的方法。在上面的代码中,该函数将返回一个int
和(可能)修改bar
。
Another similar approach is to use an out
parameter. An out
parameter is identical to a ref
parameter with an additional, compiler enforced rule. This rule is that if you pass an out
parameter into a function, that function is required to set its value prior to returning. Besides that rule, an out
parameter works just like a ref
parameter.
另一种类似的方法是使用out
参数。参数与具有附加的编译器强制规则的out
参数相同ref
。这条规则是,如果您将out
参数传递给函数,则该函数需要在返回之前设置其值。除了该规则之外,out
参数的工作方式与ref
参数一样。
The final approach (and the best in most cases) is to create a type that encapsulates both values and allow the function to return that:
最后一种方法(在大多数情况下是最好的)是创建一个封装这两个值并允许函数返回的类型:
class FooBar
{
public int i { get; set; }
public Bar b { get; set; }
}
FooBar Foo(Bar bar) { }
This final approach is simpler and easier to read and understand.
最后一种方法更简单,更容易阅读和理解。
回答by blitzkriegz
Mainly two methods are there. 1. Use out/ref parameters 2. Return an Array of objects
主要有两种方法。1. 使用 out/ref 参数 2. 返回一个对象数组
回答by Rikin Patel
you can try this "KeyValuePair"
你可以试试这个“KeyValuePair”
private KeyValuePair<int, int> GetNumbers()
{
return new KeyValuePair<int, int>(1, 2);
}
var numbers = GetNumbers();
Console.WriteLine("Output : {0}, {1}",numbers.Key, numbers.Value);
Output :
输出 :
Output : 1, 2
输出:1、2