C#交換兩個變量值的幾種方法總結(jié)
在學習.Net/C#或者任何一門面向?qū)ο笳Z言的初期,大家都寫過交換兩個變量值,通常是通過臨時變量來實現(xiàn)。本篇使用多種方式實現(xiàn)兩個變量值的交換。
假設int x =1; int y = 2;現(xiàn)在交換兩個變量的值。
使用臨時變量實現(xiàn)
static void Main(string[] args)
{
int x = 1;
int y = 2;
Console.WriteLine("x={0},y={1}",x, y);
int temp = x;
x = y;
y = temp;
Console.WriteLine("x={0},y={1}", x, y);
Console.ReadKey();
}使用加減法實現(xiàn)
試想, 1+2=3,我們得到了兩數(shù)相加的結(jié)果3。3-2=1,把1賦值給y,y就等于1; 3-1=2,把2賦值給x,這就完成了交換。
static void Main(string[] args)
{
int x = 1;
int y = 2;
Console.WriteLine("x={0},y={1}",x, y);
x = x + y; //x = 3
y = x - y; //y = 1
x = x - y; //x = 2
Console.WriteLine("x={0},y={1}", x, y);
Console.ReadKey();
}使用ref和泛型方法實現(xiàn)
如果把交換int類型變量值的算法封裝到方法中,需要用到ref關鍵字。
static void Main(string[] args)
{
int x = 1;
int y = 2;
Console.WriteLine("x={0},y={1}",x, y);
Swap(ref x, ref y);
Console.WriteLine("x={0},y={1}", x, y);
Console.ReadKey();
}
static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = x;
}如果交換string類型的變量值,就要寫一個Swap方法的重載,讓其接收string類型:
static void Main(string[] args)
{
string x = "hello";
string y = "world";
Console.WriteLine("x={0},y={1}",x, y);
Swap(ref x, ref y);
Console.WriteLine("x={0},y={1}", x, y);
Console.ReadKey();
}
static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = x;
}
static void Swap(ref string x, ref string y)
{
string temp = x;
x = y;
y = x;
}如果交換其它類型的變量值呢?我們很容易想到通過泛型方法來實現(xiàn),再寫一個泛型重載。
static void Main(string[] args)
{
string x = "hello";
string y = "world";
Console.WriteLine("x={0},y={1}",x, y);
Swap<string>(ref x, ref y);
Console.WriteLine("x={0},y={1}", x, y);
Console.ReadKey();
}
static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = x;
}
static void Swap(ref string x, ref string y)
{
string temp = x;
x = y;
y = x;
}
static void Swap<T>(ref T x, ref T y)
{
T temp = x;
x = y;
y = temp;
}使用按位異或運算符實現(xiàn)
對于二進制數(shù)字來說,當兩個數(shù)相異的時候就為1, 即0和1異或的結(jié)果是1, 0和0,以及1和1異或的結(jié)果是0。關于異或等位運算符的介紹在這里:http://m.fzitv.net/article/260847.htm
舉例,把十進制的3和4轉(zhuǎn)換成16位二進制分別是:
x = 0000000000000011;//對應十進制數(shù)字3
y = 0000000000000100; //對應十進制數(shù)字4
把x和y異或的結(jié)果賦值給x:x = x ^ y;
x = 0000000000000111;
把y和現(xiàn)在的x異或,結(jié)果賦值給y:y = y ^ x
y = 0000000000000011;
把現(xiàn)在的x和現(xiàn)在的y異或,結(jié)果賦值給x:x = x ^ y
x = 0000000000000100;
按照上面的算法,可以寫成如下:
static void Main(string[] args)
{
int x = 1;
int y = 2;
Console.WriteLine("x={0},y={1}",x, y);
x = x ^ y;
y = y ^ x;
x = x ^ y;
Console.WriteLine("x={0},y={1}", x, y);
Console.ReadKey();
}以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內(nèi)容請查看下面相關鏈接
相關文章
其實/FileShare就是控制文件流的“訪問權(quán)限”,當然,這僅僅是入門的文件操作,自己做了筆記,也希望能給大家?guī)韼椭?/div> 2014-01-01
c#中WinForm用OpencvSharp實現(xiàn)ROI區(qū)域提取的示例
已經(jīng)自學OpencvSharp一段時間了,現(xiàn)在就分享一下我的學習過程,本文主要介紹了c#中WinForm用OpencvSharp實現(xiàn)ROI區(qū)域提取的示例,具有一定的參考價值,感興趣的可以了解一下2022-05-05最新評論

