輕松進修C#的運算符。本站提示廣大學習愛好者:(輕松進修C#的運算符)文章只能為提供參考,不一定能成為您想要的結果。以下是輕松進修C#的運算符正文
1、字符串聯接運算符(“+”)
字符串聯接運算符的感化是將兩個字符串聯接在一路,構成一個新的字符串。在法式中湧現(“提醒字符”+變量),這裡起字符銜接感化。
用一個例子來講明字符串聯接運算符的感化:
<span >using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 運算符
{
class Program
{
static void Main(string[] args)
{
int a = 26;
int b = 10;
int c;
c= a + b;
Console.WriteLine("天然表達式a+b的值為:{0}",a);//C#中的輸入格局
Console.WriteLine("{0}+{1}={2}",a,b,a+b);//C#的輸入格局
Console.WriteLine("天然表達式a+b的值為:"+a);//在這裡“+”起到字符的銜接感化
Console.WriteLine("a+b的前往值類型: {0}",(a+b).GetType());//顯示前往值c的數據類型
string str1 = "This is ";
string str2 = "a new string";
Console.WriteLine(str1+str2);//在這裡“+”起到字符串的銜接感化
Console.ReadLine();
}
}
}
</span>
輸入的成果為:

2、is運算符
is運算符用於靜態檢討對象的運轉時能否與給定類型兼容。其格局為;表達式 is 類型,運轉的成果前往一個布爾值,表現“表達式”的類型if歐可經由過程援用轉換,裝箱轉換或拆箱轉換(其他轉換不在is運算符斟酌之列),然後轉換為要斷定的“類型”。
上面舉例解釋運算符的感化:
<span >using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 運算符
{
class Program
{
static void Main(string[] args)
{
object a = 10;
if (a is bool)
{
Console.WriteLine("b是一個bool類型");
}
else
{
Console.WriteLine("b不是一個bool類型");
}
Console.ReadLine();
}
}
}</span>
輸入的成果為:b不是一個bool類型
3、as運算符
as運算符用於將一個值顯式地轉換(應用援用轉換或裝箱轉換,假如履行其他的轉換,應當為強迫轉換表達式履行這些轉換)為一個給定的援用類型。其格局為:表達式 as 援用類型。當as指定的轉換不克不及完成時,則運算成果為null。用戶可經由過程這點斷定一個表達式能否為某一數據類型。
經由過程一個例子來講明數組nums中的每一個元素能否為字符串類型:
<span >using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 運算符
{
class Program
{
static void Main(string[] args)
{
object[] nums=new object[3];
nums[0] = "123";
nums[1] = 456;
nums[2] = "字符串";
for (int i = 0; i < nums.Length; i++)//遍歷數組nums的一切元素
{
string s = nums[i] as string;//將對應的元素轉換為字符串
Console.WriteLine("nums[{0}]:",i);
if (s!=null)
{
Console.WriteLine("'"+s+"'");
}
else
{
Console.WriteLine("不是一個字符串");
}
}
Console.ReadLine();
}
}
}
</span>
輸入的成果為:

4、當應用關系運算符比擬的是兩個字符的年夜小時的法式
<span >using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 運算符
{
class Program
{
static void Main(string[] args)
{
bool b1;
char char1 = 'c';
char char2 = 'd';
byte[] unicode1 = Encoding.Unicode.GetBytes(new char[] { char1 });//將字符c的Unicode轉換成字符串
byte[] unicode2 = Encoding.Unicode.GetBytes(new char[] { char2 });
Console.WriteLine("字符'c'的Unicode值為:{0}", unicode1[0]);
Console.WriteLine("字符'd'的Unicode值為:{0}", unicode2[0]);
b1 = char1 > char2;
Console.WriteLine("char1>char2值為:{0}",b1);
Console.ReadLine();
Console.ReadLine();
}
}
}</span>
輸入的成果為:

5、C#中的裝箱與拆箱
簡略的說一下C#說話中的裝箱與拆箱:
裝箱:將值類型轉換為援用類型。
拆箱:將援用類型轉換為值類型。
具體內容請參考本文:《輕松進修C#的裝箱與拆箱》
以上就是本文的全體內容,願望贊助年夜家更好的進修懂得C#的運算符。