C#語言基礎-01
寫這兩篇文章的目的是爲了備忘、 C#語言在大學讀書時候學過、當時做過一些東西、但是由於從事的主要工作和C#無關便忘記了。 近來公司增加了Unity業務、 寫Unity主要是C# 和js 想來C# 的語法結構和Java很相似、於是採用了C#語言作爲公司遊戲項目的主要語言。
本系列主要分上中下三篇文章來記錄。 分別牽涉到C# 中的初級、中級、高級內容。
1. HelloWorld
先來個HelloWorld
// 這裏是註釋 下面的是引入命名空間
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//定義命名空間 從{開始,到}結束
namespace _samuelnotes.csTest {
//定義類
class Program {
//定義一個Main方法
static void Main() {
//方法體
Console.Write("Hello world1!");
Console.Write("Hello world2!");
Console.Write("Hello world3!");
Console.WriteLine("Hello 1");
Console.WriteLine("Hello 2");
Console.WriteLine("Hello 3");
Console.WriteLine("兩個數相加{0}+{1}={2}", 3, 34, 34);
Console.WriteLine("Three integers are {1},{0} and {1}", 3, 5);
Console.ReadKey();
}
}
}
- 變量類型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
byte myByte = 34;
int score = 6000;
long count = 10000000300;
Console.WriteLine("byte:{0} int:{1} long:{2}",myByte,score,count);
//// 這個類似於java中的format 方法、 可以按照參數列表自動匹配的打印方式。
float myFloat = 12.5f;
double myDouble = 12.6;
Console.WriteLine("float:{0} double:{1}",myFloat,myDouble);
char myChar = 'a';
string myString = "";
string myString2 = "a";
bool myBool = false;//布爾類型
Console.WriteLine("char:{0} string1:{1} string2:{2} bool:{3}",myChar,myString,myString2,myBool);
Console.ReadKey();
}
}
}
3.@符號字符串
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
// Ctrl + k 然後 Ctrl + C 這個是一個組合快捷鍵 可以註釋選中行
// Ctrl + k然後Ctrl +U 取消註釋選中行
//當在字符串前面加上一個@字符的時候,我們就可以把一個字符串定義在多行
// 編譯器不會再去識別字符串中的轉義字符
// 如果需要在字符串中表示一個雙引號的話,需要使用兩個雙引號
string str1 = @"I'm a good man.
You are bad girl!";
Console.WriteLine(str1);
string str2 = @"I'm a good man. \n"" You are bad girl!";
Console.WriteLine(str2);
//使用@字符的第二個好處
string path = "c:\\xxx\\xx\\xxx.doc";
Console.WriteLine(path);
string path2 = @"c:\xxx\xx\xxx.doc";
Console.WriteLine(path2);
Console.ReadKey();
}
}
}
4. 數學基礎運算
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
int num1 = 45;
int num2 = 13;
//int res1;
//res1 = num1 + num2;
int res1 = num1 + num2;
int res2 = num1 - num2;
int res3 = num1 * num2;
int res4 = num1 / num2;
int res5 = num1 % num2;
double res = 123.4 % 2;
int num3 = 45;
double num4 = 3.1;
double res6 = num3 + num4;
//加減乘除求餘兩邊的操作數都是整數的話,結果還是整數,不過不能被整除的話,自動略去小數部分
Console.WriteLine("加法的結果:{0} \n 減法的結果:{1} \n乘法的結果:{2}\n除法的結果:{3}\n求餘運算的結果:{4}", res1, res2, res3, res4, res5);
Console.WriteLine(res);
//關於加法運算符更多的使用
//1.字符串相加 用來連接兩個字符串 返回一個字符串
string str1 = "123adb";
string str2 = "www.samuelnotes.cn";
string str = str1 + str2;
//Console.WriteLine(str);
//2,當一個字符串跟一個數字相加的話,首先把數字轉變成字符串,然後連接起來 結果是字符串
//string str1 = "123";
//int num = 456;
//string res = str1 + num;
Console.WriteLine(res);
Console.ReadKey();
}
}
}
打印結果:
加法的結果:58
減法的結果:32
乘法的結果:585
除法的結果:3
求餘運算的結果:6
1.40000000000001
1.40000000000001
5.自增自減和賦值操作
int num1 = 45;
//num1++;
//++num1;//++不管是放在操作數的前面還是後面,都是讓操作數加1
//int res = num1++;// 45
int res = ++num1;//46 ++如果放在前面會先進行自增,然後再進行其餘的運算,如果放在操作數的後面,會先使用操作數進行運算,然後讓操作數自增
Console.WriteLine(res + ":" + num1);
//int num1 = 45;
//int res = num1--;//45
//int res2 = --num1;//43
//Console.WriteLine(res+":"+res2);
Console.ReadKey();
簡單說兩句, 自增自減屬於簡寫、 無論放在操作數的前邊還是後邊、都可以讓操作數+1 或者-1 ; ++如果放在前面會先進行自增,然後再進行其餘的運算,如果放在操作數的後面,會先使用操作數進行運算,然後讓操作數自增
int num1 = 34;//這個是最常用 最基本的賦值運算符
num1 += 12;// num1 = num1+12;//46
num1 -= 12;// num1 = num1 - 12;//34
num1 *= 2;//num1 = num1*2;// 68
num1 /= 2;//num1 =num1/2//34
num1 %= 4;//num1 = num1%4;//2
Console.WriteLine(num1);
Console.ReadKey();
是不是很簡單、我們繼續。
6.從鍵盤上讀取字符串
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
//string str = Console.ReadLine();//用來接收用戶輸入的一行文本,也叫做一行字符串,按下換行就是回車的時候結束
//Console.WriteLine(str);
//string str = "123";
//int num = Convert.ToInt32(str);//這個方法可以把一個整數的字符串轉化成整數32
//num++;
//Console.WriteLine(num);
//string str = Console.ReadLine();
//int num = Convert.ToInt32(str);
//Console.WriteLine(num);
string str = Console.ReadLine();
/// 類型轉換
double num = Convert.ToDouble(str);//這個可以把用戶輸入的小數的字符串轉化成double浮點類型
Console.WriteLine(num);
Console.ReadKey();
}
}
}
輸入、顯示和
Console.WriteLine("請輸入第一個數字");
string str1 = Console.ReadLine();
int num1 = Convert.ToInt32(str1);
Console.WriteLine("請輸入第二個數字");
string str2 = Console.ReadLine();
int num2 = Convert.ToInt32(str2);
int sum = num1 + num2;
Console.WriteLine("您輸入的兩個數字的和爲");
Console.WriteLine(sum);
Console.ReadKey();
7.運算符優先級
在任何語言裏、如果表達式過長、都是需要有優先級的,C# 也不例外。 來個例子,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
int num = 12 + 90;
int num1 = 12 + 90*2/4%4;//在程序中的表達式中,運算符是有優先級的,先進行優先級高 的運算符的運算
int num2 = (12 + 90) * 2;//我們可以通過()來改變運算符的優先級,()內的運算總是最先執行
Console.WriteLine(num);
Console.WriteLine(num1);
Console.WriteLine(num2);
Console.ReadKey();
}
}
}
總結上一段內容、 來個練習,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args) {
//Console.WriteLine("請輸入上底");
//string str1 = Console.ReadLine();
//double num1 = Convert.ToDouble(str1);
//Console.WriteLine("請輸入下底");
//string str2 = Console.ReadLine();
//double num2 = Convert.ToDouble(str2);
//Console.WriteLine("請輸入梯形的高");
//string str3 = Console.ReadLine();
//double num3 = Convert.ToDouble(str3);
//Console.WriteLine("梯形的面積是:");
//double res = ((num1 + num2)*num3)/2;
//Console.WriteLine(res);
Console.WriteLine("請輸入圓的半徑");
string str = Console.ReadLine();
double n = Convert.ToDouble(str);
Console.WriteLine("圓的周長是:" + (2 * n * 3.14));
Console.WriteLine("圓的面積是:" + (n * n * 3.14));
Console.ReadKey();
}
}
}
8.Boolean運算
如果有一定的編程語法基礎、則曉得布爾運算是什麼了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
int score = 30;
bool res = score >= 50;// 在這裏>=就是一個比較運算符,用來比較score是否大於等於50,如果是的話返回true,如果不是的話返回false
Console.WriteLine(res==false);
bool parsres = false;
bool tryparse = Boolean.TryParse("true",out parsres);
Console.WriteLine("tryparse: {0} parseres: {1}", tryparse,parsres);
int num1 = 34;
int num2 = 67;
bool res1 = num1 == num2;//false
bool res2 = num1 != num2;//true
bool res3 = num1 < num2;//true
bool res4 = num1 > num2;//false
bool res5 = num1 <= num2;//true;
bool res6 = num1 >= num2;//false
Console.WriteLine(res1);
Console.WriteLine(res2);
Console.WriteLine(res3);
Console.WriteLine(res4);
Console.WriteLine(res5);
Console.WriteLine(res6);
/////////// 布爾條件運算
bool var1 = true;
bool var2 = false;
bool res = !var1;//!是取反操作 當var1爲true、的時候,返回false,當var1爲false的時候,var1返回true
bool res1 = var1 & var2;//false;
bool res2=var1 | var2;//true;
bool res3 = var1 ^ var2;//true;
Console.WriteLine(res);
Console.WriteLine(res1);
Console.WriteLine(res2);
Console.WriteLine(res3);
// && ||
bool res = var1 && var2;//false; &&:而且
bool res2 = var1 || var2;//treu ||:或
Console.ReadKey();
}
}
}
9.goto語句
雖然說不推薦使用這個語法關鍵字、因爲java中沒有goto、 估計這語法八成是從C++ 中繼承過來的, 不推薦的原因是,頻繁使用goto語句、容易造成語句混亂、增加閱讀難度、維護成本。 但是別人如果寫了、你要看懂、這是必備技能。
看一個例子。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
int myInteger = 5;
// 這裏定義標籤
goto mylabel; //goto語句用來控制程序跳轉到某個標籤的位置
myInteger ++;
mylabel:Console.WriteLine(myInteger);
Console.ReadKey();
}
}
}
控制檯打印 5 、 爲什麼不++了呢、 因爲剛開始執行 就跳轉到了mylabel標籤這裏。 很簡單不再贅述、我們繼續。
10. if語句
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
//bool var = false;
//if(var==false)
// Console.WriteLine("-------");
//Console.WriteLine("if語句後面的語句");
string str = Console.ReadLine();
int score = Convert.ToInt32(str);
//if(score>50)
// Console.WriteLine("您輸入的分數大於50分");
//if(score<=50)
// Console.WriteLine("您輸入的分數小於等於50");
// if else 只能執行其中一個分支,而且肯定會執行其中一個分支
if (score > 50)
{
score++;
Console.WriteLine("您輸入的分數大於50"+score);
}
else
{
score--;
Console.WriteLine("您輸入的分數小於等於50"+score);
}
Console.ReadKey();
}
}
}
再來個 例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args) {
Console.WriteLine("您考了多少分?");
string str = Console.ReadLine();
int score = Convert.ToInt32(str);
if (score >= 90)
{
Console.WriteLine("優秀");
}else if (score >= 80 && score <= 89)
{
Console.WriteLine("良");
}else if (score >= 60 && score <= 79)
{
Console.WriteLine("中");
}
else
{
Console.WriteLine("差,繼續努力哦!");
}
Console.ReadKey();
}
}
}
11.三元運算符
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
//int myInteger = 100;
//string resStr = (myInteger < 10)
// ? "Less than 10"
// : "Greater than or equal to 10";
//Console.WriteLine(resStr);
string str = Console.ReadLine();
int score = Convert.ToInt32(str);
string resStr = score > 50 ? "您輸入的分數大於50" : "您輸入的分數小於等於50";
Console.WriteLine(resStr);
Console.ReadKey();
}
}
}
這裏簡單說一句、 條件 ? true : false ;
11.switch條件語句
這個和java switch 中的語句一致、 沒什麼說的、 栗子。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
int state = 5;
switch (state)
{
case 0:
Console.WriteLine("當前是開始界面");
break;
case 1:
Console.WriteLine("當時是戰鬥中");
break;
case 2:
Console.WriteLine("遊戲暫停");
break;
case 3:
Console.WriteLine("遊戲勝利");
break;
case 4:
case 5:
Console.WriteLine("遊戲失敗");
break;
default:
Console.WriteLine("當前state超出了遊戲狀態的取值範圍");
break;
}
Console.ReadKey();
}
}
}
12.循環語句
while 循環
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args) {
//while (true)//死循環 一直執行循環體 根本停不下來
//{
// Console.WriteLine("www.samuelnotes.cn");
//}
int index = 1;
// 執行滿足條件時進入語句塊中進行循環。
while (index<=9)
{
Console.WriteLine(index);//1 2 3 4 5 6 7 8 9
index++;
}
Console.ReadKey();
}
}
}
do … while 循環
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
//do
//{
// Console.WriteLine("這裏是do while的循環體");
//} while (true);//這個是一個死循環
int index = 1;
do
{
Console.WriteLine(index);
index++;
} while (index <= 9);
//do while循環會首先執行一次循環體,然後進行條件判斷 循環體的執行次數>=1
//while循環會進行條件判斷,然後根據判斷的結果去判定是否去執行循環體,循環體的執行次數>=0
Console.ReadKey();
}
}
}
for 循環
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
//for (;;)//初始化條件 ,和循環的判斷條件都不寫的話 就是一個死循環 這裏相當於 while (true)
//{
//}
//int index = 1;
//for (;index<=9;)
//{
// Console.WriteLine(index);
// index++;
//}
for (int index = 1;index<=9;index++)
{
Console.WriteLine(index);
}
Console.ReadKey();
}
}
}
break 和continue 關鍵字
break 跳出關鍵字
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
//int index = 1;
//while (true)
//{
// Console.WriteLine(index);
// if (index == 9)
// {
// break;//跳出最近的循環結構,執行下一行代碼
// }
// index++;
//}
while (true)
{
string str = Console.ReadLine();
if (str == "0")
{
break;
}
else
{
Console.WriteLine(str);
}
}
//Console.ReadKey();
}
}
}
continue 關鍵字
int sum =0;
for ( int num = 0 ; num<= 100; num++)
{
if (num%2 == 1)
{
continue;
}
sum += num;
}
continue 直接跳轉至下一個循環 。
13.顯式轉換與隱式轉換
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
//byte myByte = 123;
//int myInt = myByte;//把一個小類型的數據複製給大類型的變量的時候,編譯器會自動進行類型的轉換;
//myByte = (byte)myInt;//當把一個大類型賦值給一個小類型的變量的時候 ,需要進行顯示轉換(強制類型轉換),就是加上括號,裏面寫需要轉換的類型
//float myfloat = myInt;
//myInt = (int)myfloat;
//char c = 'a';
//myfloat = c;
string str = "123.3";
int num = Convert.ToInt32(str);//當字符串裏面存儲的是整數的時候,就可以轉化成int double類型,否則出現異常
//當字符串裏面是一個小數的時候,就可以轉化成double類型
int mynum = 234234;
string str2 = Convert.ToString(mynum);//它可以把一個int float double byte類型轉換成字符串
string str3 = mynum + "";//一個int float double類型直接加上一個空的字符串,相當於把這個數字轉化成一個字符串
Console.WriteLine(num);
Console.ReadKey();
}
}
}
註釋很清楚了、 我們繼續。
14.枚舉結構
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
//枚舉類型的定義
enum GameState:byte//修改該枚舉類型的存儲類型,默認爲int
{
Pause = 100, // 默認代表的是整數0
Failed = 101,// 默認代表的是整數1
Success=102,// 默認代表的是整數2
Start=200// 默認代表的是整數3
}
class Program
{
static void Main(string[] args) {
////利用定義好的枚舉類型 去聲明變量
//GameState state = GameState.Start;
//if (state == GameState.Start)//枚舉類型比較
//{
// Console.WriteLine("當前處於遊戲開始狀態");
//}
//Console.WriteLine(state);
//int state =3;
//if (state == 3)
//{
// Console.WriteLine("當前處於遊戲開始界面");
//}
GameState state = GameState.Start;
int num = (int)state;
Console.WriteLine(num);
Console.ReadKey();
}
}
}
枚舉這東西不是什麼新鮮的東西、 C++ 中也有、只不過叫做結構體。
15.結構體
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
//我們可以把結構體當成,幾個類型組成了一個新的類型
//比如下面的這個就是使用了3個float類型的變量,來表示一個座標類型
struct Position
{
public float x;
public float y;
public float z;
}
enum Direction
{
West,
North,
East,
South
}
struct Path
{
public float distance;
public Direction dir;
}
class Program {
static void Main(string[] args)
{
//通過三個float類型的變量來表示一個敵人的座標
//float enemy1X = 34;
//float enemy1Y = 1;
//float enemy1Z = 34;
//float enemy2X = 34;
//float enemy2Y = 1;
//float enemy2Z = 34;
//當使用結構體聲明變量的時候,相當於使用結構體中所有的變量去聲明
//Position enemy1Position;
//enemy1Position.x = 34;//可以通過.加上屬性名來訪問結構體中指定的變量
////使用結構體讓程序變得更清晰
//Position enemy2Position;
Path path1;
path1.dir = Direction.East;
path1.distance = 1000;
}
}
}
16.數組與數組遍歷
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
//第一種 數組的初始化方式
//int[] scores = {23,43,432,42,34,234,234,2,34} ;//使用這種方式賦值的時候,一定要注意 在數組聲明的時候賦值
//第二種數組創建的方式
//int[] scores = new int[10];
//int[] scores;
//scores = new int[10];
//int[] scores = new int[10]{3,43,43,242,342,4,234,34,234,5};
//Console.WriteLine(scores[10]);//當我們訪問一個索引不存在的值的時候,會出現異常exception
//char[] charArray = new char[2]{'a','b'};
//Console.WriteLine(charArray[1]);
string[] names = new string[]{"taikr","baidu","google","apple"};
Console.WriteLine(names[0]);
int[] scores = {23, 2, 32, 3, 34, 35, 45, 43, 543};
//scores.Length//得到數組的長度
//for (int i = 0; i < scores.Length; i++)
//{
// Console.WriteLine(scores[i]);
//}
//int i = 0;
//while (i<scores.Length)
//{
// Console.WriteLine(scores[i]);
// i++;
//}
foreach (int temp in scores )//foreach會依次取到數組中的值,然後賦值給temp,然後執行循環體
{
Console.WriteLine(temp);
}
Console.ReadKey();
}
}
}
17.字符串的處理
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args)
{
string str = " www.Samuelnotes.CN ";
//str.Length//可以通過.Length訪問到一個字符串的長度
//for (int i = 0; i < str.Length; i++)
//{
// Console.WriteLine(str[i]);
//}
//string res = str.ToLower();//把字符串轉化成小寫 並返回,對原字符串沒有影響
//string res = str.ToUpper();//把字符串轉化成大寫 並返回,對原字符串沒有影響
//string res = str.Trim();//去掉字符串前面和後面的空格,對原字符串沒有影響
//string res = str.TrimStart();
//string res = str.TrimEnd();
string[] strArray=str.Split('.');//把原字符串按照指定的字符進行拆分 ,得到一個拆分後的字符串數組
Console.WriteLine(str+"|");
//Console.WriteLine(res + "|");
foreach (string temp in strArray)
{
Console.WriteLine(temp);
}
Console.ReadKey();
}
}
}
再來個練習
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Main(string[] args) {
/// 隨機數字
//Random random = new Random();
//int number = random.Next(0, 51);
//Console.WriteLine("我有一個數字,請您猜猜是多少,請您輸入一個0-50之間的數");
//while (true)
//{
// int temp = Convert.ToInt32(Console.ReadLine());
// if (temp < number)
// {
// Console.WriteLine("請猜小了,請繼續猜");
// }else if (temp > number)
// {
// Console.WriteLine("請猜大了,請繼續猜");
// }
// else
// {
// Console.WriteLine("您猜對了,遊戲結束");
// break;
// }
//}
string str = Console.ReadLine();
string tempStr = "";
for (int i = 0; i < str.Length; i++)
{
if (str[i] >= 'a' && str[i] <= 'z') { //說明這個字符是一個小寫字母
int num = str[i];
num += 3;
char temp = (char)num;//取得字母向後移動三個位置後的字母
if (temp > 'z')
{
temp =(char) (temp - 'z' + 'a' - 1);//如果超出26個字母的範圍,就轉換到開頭'a'
}
tempStr += temp;
}else if (str[i] >= 'A' && str[i] <= 'Z')
{
int num = str[i];
num += 3;
char temp = (char) num; //取得字母向後移動三個位置後的字母
if (temp > 'Z') {
temp = (char)(temp - 'Z' + 'A' - 1);//如果超出26個字母的範圍,就轉換到開頭'a'
}
tempStr += temp;
}
else
{
tempStr += str[i];
}
}
Console.WriteLine(tempStr);
Console.ReadKey();
}
}
}
18.函數的定義
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static void Write()// void 表示空的返回值,就是不需要返回值
{
//這裏是函數體也叫做方法體,這裏可以寫0行 ,一行或者多行語句
Console.WriteLine("Text output from function");
return;//這個語句用來結束當前函數
}
static int Plus(int num1,int num2)//函數定義的時候,參數我們叫做形式參數(形參),num1跟num2在這裏就是形參,形參的值是不確定的
{
int sum = num1 + num2;
return sum;
}
static void Main(string[] args) {
Write();//函數的調用 函數名加上括號 ,括號內寫參數
int num1 = 45;
int num2 = 90;
int res1 = Plus(num1, num2);//當調用函數的時候,這裏傳遞的參數就是實際參數(實參),實參的值會傳遞給形參做運算
int res2 = Plus(45, 20);//這裏定義了res1和res2來接受方法的返回值
Console.WriteLine(res1);
Console.WriteLine(res2);
Console.ReadKey();
}
}
}
例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static int[] GetDivisor(int number)
{
int count = 0;
for (int i = 1; i <= number; i++)
{
if (number%i == 0)
{
count++;
}
}
int[] array = new int[count];
int index = 0;
for (int i = 1; i <= number; i++) {
if (number % i == 0)
{
array[index] = i;
index++;
}
}
return array;
}
static int Max(int[] array)
{
int max = array[0];
for (int i = 1; i < array.Length; i++)
{
if (array[i] > max)
{
max = array[i];
}
}
return max;
}
static void Main(string[] args)
{
int num = Convert.ToInt32(Console.ReadLine());
int[] array = GetDivisor(num);
foreach (int temp in array)
{
Console.Write(temp + " ");
}
//int[] array = {234, 4, 5, 435, 35, 3, 53, 5, 345, 35, 2342343, 45};
//Console.WriteLine( Max(array) );
Console.ReadKey();
}
}
}
參數和不確定參數
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static int Sum(int[] array)//如果一個函數定義了參數,那麼在調用這個函數的時候,一定要傳遞對應類型的參數,否則無法調用(編譯器編譯不通過)
{
int sum = 0;
for (int i = 0; i < array.Length; i++)
{
sum += array[i];
}
return sum;
}
static int Plus(params int[] array)
//這裏定義了一個int類型的參數數組,參數數組和數組參數(上面的)的不同,在於函數的調用,調用參數數組的函數的時候,我們可以傳遞過來任意多個參數,然後編譯//器會幫我們自動組拼成一個數組,參數如果是上面的數組參數,那麼這個數組我們自己去手動創建
{
int sum = 0;
for (int i = 0; i < array.Length; i++) {
sum += array[i];
}
return sum;
}
static void Main(string[] args)
{
int sum = Sum(new int[] {23, 4, 34, 32, 32, 42, 4});
Console.WriteLine(sum);
//int sum2 = Plus(23, 4, 5, 5, 5, 32, 423, 42, 43,23,42,3);//參數數組就是幫我們 減少了一個創建數組的過程
int sum2 = Plus(new int[] { 23, 4, 5, 5, 5, 32, 423, 42, 43, 23, 42, 3 });//參數數組就是幫我們 減少了一個創建數組的過程
Console.WriteLine(sum2);
Console.ReadKey();
}
}
}
19.結構函數定義與使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Schema;
namespace _samuelnotes.cstest {
struct CustomerName
{
public string firstName;
public string lastName;
public string GetName()
{
return firstName + " " + lastName;
}
}
struct Vector3
{
public float x;
public float y;
public float z;
public double Distance()
{
return Math.Sqrt(x*x + y*y + z*z);
}
}
class Program {
static void Main(string[] args)
{
//CustomerName myName;
//myName.firstName = "siki";
//myName.lastName = "Liang";
////Console.WriteLine("My name is "+myName.firstName+" "+myName.lastName);
//Console.WriteLine("My name is "+myName.GetName());
Vector3 myVector3;
myVector3.x = 3;
myVector3.y = 3;
myVector3.z = 3;
Console.WriteLine(myVector3.Distance());
Console.ReadKey();
}
}
}
20.重載函數
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static int MaxValue(params int[] array)
{
Console.WriteLine("int類型的maxvalue被調用 ");
int maxValue = array[0];
for (int i = 1; i < array.Length; i++)
{
if (array[i] > maxValue)
{
maxValue = array[i];
}
}
return maxValue;
}
static double MaxValue(params double[] array)
{
Console.WriteLine("double類型的maxvalue被調用 ");
double maxValue = array[0];
for (int i = 1; i < array.Length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
static void Main(string[] args)
{
int res = MaxValue(234, 23, 4);//編譯器會根據你傳遞過來的實參的類型去判定調用哪一個函數
double res2 = MaxValue(23.34, 234.5, 234.4);
Console.WriteLine(res);
Console.WriteLine(res2);
Console.ReadKey();
}
}
}
21.委託使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
//定義一個委託跟函數差不多,區別在於
//1,定義委託需要加上delegate關鍵字
//2,委託的定義不需要函數體
public delegate double MyDelegate(double param1, double param2);
class Program {
static double Multiply(double param1, double param2)
{
return param1*param2;
}
static double Divide(double param1, double param2)
{
return param1/param2;
}
static void Main(string[] args)
{
MyDelegate de;//利用我們定義的委託類型聲明瞭一個新的變量
de = Multiply;//當我們給一個委託的變量賦值的時候,返回值跟參數列表必須一樣,否則無法賦值
Console.WriteLine(de(2.0, 34.1));
de = Divide;
Console.WriteLine( de(2.0,34.1) );
Console.ReadKey();
}
}
}
22.函數遞歸
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _samuelnotes.cstest {
class Program {
static int F(int n)
{
if (n == 0) return 2;//這兩個是函數終止遞歸的條件
if (n == 1) return 3;
return F(n - 1) + F(n - 2);//函數調用自身 叫做遞歸調用
}
static void Main(string[] args)
{
//////// 費波納茨函數
int res = F(40);
Console.WriteLine(res);
int res2 = F(2);
Console.WriteLine(res2);
}
}
}
總結
多思考、上手敲代碼、 調試調試、多試試。 如果有問題可以評論區留言共同學習進步。