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);
}
}
}
总结
多思考、上手敲代码、 调试调试、多试试。 如果有问题可以评论区留言共同学习进步。