我读了C++ version of this question,但并不是真的理解它。
有没有人能清楚地解释一下,是否可以用C#实现,以及如何实现?
发布于 2012-04-23 18:24:13
在C# 7和更高版本中,请参阅this answer。
在以前的版本中,您可以使用.NET 4.0+'s Tuple
例如:
public Tuple<int, int> GetMultipleValue()
{
return Tuple.Create(1,2);
}具有两个值的元组具有Item1和Item2属性。
发布于 2016-04-06 04:19:33
既然C# 7已经发布,您就可以使用新的包含的元组语法
(string, string, string) LookupName(long id) // tuple return type
{
... // retrieve first, middle and last from data storage
return (first, middle, last); // tuple literal
}然后可以像这样使用它:
var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item3}.");您还可以为您的元素提供名称(这样它们就不是"Item1“、"Item2”等)。您可以通过在签名或返回方法中添加名称来完成此操作:
(string first, string middle, string last) LookupName(long id) // tuple elements have names或
return (first: first, middle: middle, last: last); // named tuple elements in a literal它们也可以被解构,这是一个非常好的新特性:
(string first, string middle, string last) = LookupName(id1); // deconstructing declaration请查看this link,了解更多可以完成哪些操作的示例:)
发布于 2015-06-04 07:04:41
您可以使用三种不同的方法
1.REF/ out参数
使用ref:的
static void Main(string[] args)
{
int a = 10;
int b = 20;
int add = 0;
int multiply = 0;
Add_Multiply(a, b, ref add, ref multiply);
Console.WriteLine(add);
Console.WriteLine(multiply);
}
private static void Add_Multiply(int a, int b, ref int add, ref int multiply)
{
add = a + b;
multiply = a * b;
}使用out的:
static void Main(string[] args)
{
int a = 10;
int b = 20;
int add;
int multiply;
Add_Multiply(a, b, out add, out multiply);
Console.WriteLine(add);
Console.WriteLine(multiply);
}
private static void Add_Multiply(int a, int b, out int add, out int multiply)
{
add = a + b;
multiply = a * b;
}2.结构/类
使用结构的:
struct Result
{
public int add;
public int multiply;
}
static void Main(string[] args)
{
int a = 10;
int b = 20;
var result = Add_Multiply(a, b);
Console.WriteLine(result.add);
Console.WriteLine(result.multiply);
}
private static Result Add_Multiply(int a, int b)
{
var result = new Result
{
add = a * b,
multiply = a + b
};
return result;
}使用类:的
class Result
{
public int add;
public int multiply;
}
static void Main(string[] args)
{
int a = 10;
int b = 20;
var result = Add_Multiply(a, b);
Console.WriteLine(result.add);
Console.WriteLine(result.multiply);
}
private static Result Add_Multiply(int a, int b)
{
var result = new Result
{
add = a * b,
multiply = a + b
};
return result;
}元组3.元组
元组类
static void Main(string[] args)
{
int a = 10;
int b = 20;
var result = Add_Multiply(a, b);
Console.WriteLine(result.Item1);
Console.WriteLine(result.Item2);
}
private static Tuple<int, int> Add_Multiply(int a, int b)
{
var tuple = new Tuple<int, int>(a + b, a * b);
return tuple;
}C# 7元组
static void Main(string[] args)
{
int a = 10;
int b = 20;
(int a_plus_b, int a_mult_b) = Add_Multiply(a, b);
Console.WriteLine(a_plus_b);
Console.WriteLine(a_mult_b);
}
private static (int a_plus_b, int a_mult_b) Add_Multiply(int a, int b)
{
return(a + b, a * b);
}https://stackoverflow.com/questions/748062
复制相似问题