我有一个计算两个位置的函数,我想得到它们两个,有没有办法从同一个函数返回两个值,而不是把它们变成一个数组.我认为有一些争论或类似的东西... tnx.我的代码:
public static int Location(int p_1, int p_2, int p_3, int p_4)
{
int XLocation = p_2 - p_1;
int YLocation = p_4-p_3;
return XLocation,YLocation;
}
public void Print()
{
}
Run Code Online (Sandbox Code Playgroud)
alg*_*eat 32
有多种方法:
1)使用:
public KeyValuePair<int, int> Location(int p_1, int p_2, int p_3, int p_4)
{
return new KeyValuePair<int,int>(p_2 - p_1, p_4-p_3);
}
Run Code Online (Sandbox Code Playgroud)
要么
static Tuple<int, int> Location(int p_1, int p_2, int p_3, int p_4)
{
return new Tuple<int, int>(p_2 - p_1, p_4-p_3);
}
Run Code Online (Sandbox Code Playgroud)
2)使用自定义类 Point
public class Point
{
public int XLocation { get; set; }
public int YLocation { get; set; }
}
public static Point Location(int p_1, int p_2, int p_3, int p_4)
{
return new Point
{
XLocation = p_2 - p_1;
YLocation = p_4 - p_3;
}
}
Run Code Online (Sandbox Code Playgroud)
3)使用out
关键字:
public static int Location(int p_1, int p_2, int p_3, int p_4, out int XLocation, out int YLocation)
{
XLocation = p_2 - p_1;
YLocation = p_4 - p_3;
}
Run Code Online (Sandbox Code Playgroud)
以下是这些方法的比较:多次返回值.
最快的方式(最佳性能)是:
public KeyValuePair<int, int> Location(int p_1, int p_2, int p_3, int p_4)
{
return new KeyValuePair<int,int>(p_2 - p_1, p_4-p_3);
}
Run Code Online (Sandbox Code Playgroud)
van*_*eto 13
使用结构或类:
public struct Coordinates
{
public readonly int x;
public readonly int y;
public Coordinates (int _x, int _y)
{
x = _x;
y = _y;
}
}
public static Coordinates Location(int p_1, int p_2, int p_3, int p_4)
{
return new Coordinates(p_2 - p_1, p_4 - p_3);
}
Run Code Online (Sandbox Code Playgroud)
我发现它比使用out
关键字更漂亮.
您不能以这种方式返回2个值.但是您可以将变量作为输出变量传递,如下所示:
public static void Location(int p_1, int p_2, int p_3, int p_4, out int XLocation, out int YLocation)
{
XLocation = p_2 - p_1;
YLocation = p_4-p_3;
}
Run Code Online (Sandbox Code Playgroud)
然后你只需要将目标变量传递给方法:
int Xlocation, YLocation;
Location(int p_1, int p_2, int p_3, int p_4, out int XLocation, out int YLocation);
Run Code Online (Sandbox Code Playgroud)
它会用计算值填充它们.
从 C# 7.0 开始,您可以像这样使用元组:
(string, string) LookupName(long id) // tuple return type
{
... // retrieve first, middle and last from data storage
return (first, last); // tuple literal
}
var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item2}.");
Run Code Online (Sandbox Code Playgroud)
甚至名称:
(string first, string middle, string last) LookupName(long id)
var names = LookupName(id);
WriteLine($"found {names.first} {names.last}.");
Run Code Online (Sandbox Code Playgroud)
可在此处找到更多信息。