//可返回多个值,需要早函数外声明字段,通过函数修改字段值
private void TestFunc1(ref string key, ref int value)
{
key = "key";
value = 1;
}
private void TestFunc2(out string key, out int value)
{
key = "key";
value = 1;
}
//只能返回两个值
private KeyValuePair<string, int> TestFunc3()
{
return new KeyValuePair<string, int>("key", 1);
}
//可返回多个值,不过需要类型转换,不推荐
private List<object> TestFunc4()
{
return new List<object>() { "key", 1 };
}
//返回自定义类
public class MoreValue
{
public string key;
public int value;
}
private MoreValue TestFunc5()
{
return new MoreValue() { key = "key", value = 1 };
}
//--------------------
//Tuple元组: C# 4.0的新特性
//是一种数据结构,引用类型,具有特定数量和元素序列
//最多有八个元素,要想更多只能通过最后一个元素进行嵌套扩展,(使用值元组的嵌套和Rest属性实现)
//访问元素通过ItemX去访问,使用前需要明确元素顺序,属性名字没有实际意义
private System.Tuple<string, int> TestFunc6()
{
System.Tuple<string, int> tuple = new System.Tuple<string, int>("key", 1);
Debug.Log(tuple.Item1 + tuple.Item2);
return tuple;
}
//--------------------
//ValueTuple值元组: C# 7.0的新特性
//也是一种数据结构,是值类型,用于表示特定数量和元素序列
//值元组元素是可变的,不是只读的,值元组的数据成员是字段不是属性
private System.ValueTuple<string, int> TestFunc7()
{
System.ValueTuple<string, int> valueTuple = new System.ValueTuple<string, int>("key", 1);
Debug.Log(valueTuple.Item1 + valueTuple.Item2);
return valueTuple;
}
//ValueTuple值元组,返回值可以不明显指定ValueTuple,如(string, int)
private (string, int) TestFunc8()
{
return ("key", 1);
}
//ValueTuple值元组,返回值可以指定元素名字,方便赋值和访问
private (string key, int value) TestFunc9()
{
return (key: "key", value: 1);
}
【C#】函数返回多个值/Tuple元组/ValueTuple值元组
最新推荐文章于 2024-08-14 00:15:00 发布