一行代码交换两个数据的值
在初学时,我们交换数据一般借助中介者模式
temp
int a=10;
int b=20;
int temp=b;
b=a;
int a=temp;
C#元组,提供了简便的写法
int a = 10;
int b = 20;
Console.WriteLine($"Before swap: a = {a}, b = {b}");
// 使用元组交换两个整数的值
(a, b) = (b, a);
Console.WriteLine($"After swap: a = {a}, b = {b}");
除此之外,我们还可以交换字符串
string s1 = "11111";
string s2 = "99999";
Console.WriteLine($"Before swap: s1 = {s1}, s2 = {s2}");
// 使用元组交换两个string的值
(s1, s2) = (s2 ,s1);
Console.WriteLine($"Before swap: s1 = {s1}, s2 = {s2}");
元组的其他用法
1、解构
var employee = ("John Doe", 30, 50000.0);
var (name, age, salary) = employee;
2、使用多个值来确定唯一键
var dictionary = new Dictionary<(string, string), int>();
dictionary[("apple", "red")] = 1;
dictionary[("banana", "yellow")] = 2;
3、返回多个值
(int sum, int count) CalculateSumAndCount(IEnumerable<int> numbers)
{
int sum = 0;
int count = 0;
foreach (var number in numbers)
{
sum += number;
count++;
}
return (sum, count);
}
本文作者:孤沉
本文链接:https://www.cnblogs.com/guchen33/p/18397475
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
C#基础
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?