问题
I got a function which wants to send 2 INT
parameters back to where it has been called, but not sure what would be the best option, a Dictionary
? or a List
or an Array
EDITED
I am using .Net framework 2
回答1:
I assume you mean return 2 values to the caller. If so:
- return a
Tuple<T1, T2>
- return your own custom type which stores the desired values, like
MyOperationResult
- use
out
parameters: http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx - return a collection
It depends on what is easiest for the caller to understand, i.e. what best demonstrates your intention?
Returning a variable-size collection may not be intuitive if the result will always have two values. My preference is either a Tuple or a custom type. A Tuple has the advantage of being an existing type, but the disadvantage that it's not clear what its members mean; they are just called "Item1", "Item2", and so on.
The out
keyword is nice for operations which may not succeed and always return a bool, like public bool int.TryParse( string value, out int parsedValue )
. Here the intent is clear.
回答2:
try with this code
type1 param1;
type2 param2;
void Send(out type1 param1, out type2 param2)
or
type1 param1 = ..;//You must initialize with ref
type2 param2 = ..;
void Send(ref type1 param1, ref type2 param2)
回答3:
You can try with out parameter msdn
回答4:
If you're only ever using two ints, then I'd use a 2-tuple, a Tuple<int, int>
.
You can initialise it with its two values in the constructor:
return new Tuple<int,int>(val1, val2);
Alternatively for a variable number of outputs, a List<int>
(or perhaps just an IEnumerable<int>
depending on the intended use).
回答5:
i think i need to return it by refference, like so....
private void ReturnByRef(ref int i1, ref int i2) {
}
回答6:
Well, it depends, you'd have multiple ways to do that. If it's just two parameters you want to pass back, then you could just use "out" parameters:
class A
{
private static void foo(int param, out int res1, out int res2)
{
res1 = 1*param;
res2 = 2*param;
}
public static void main(string[] args)
{
int res1, res2;
foo(1, out res1, out res2);
// Do something with your results ...
}
回答7:
out parameter works best
static void Main()
{
int a;
int b;
someFunction(out a,out b); //the int values will be returned in a and b
Console.WriteLine(a);
Console.WriteLine(b);
}
public static void someFunction(out int x,out int y)
{
x=10;
y=20;
}
your output wil be
10
20
来源:https://stackoverflow.com/questions/11737497/sending-2-parameters-back-to-main-function