C#学习第二天
今天进行了C#的第二次学习,继续了解C#的相关知识:
方法
定义方法的过程与Java还有C++无异,所以不做过多赘述。
调用方法是可以直接调用其他类的公有方法的。
using System; namespace CalculatorApplication { class NumberManipulator { public int FindMax(int num1, int num2) { /* 局部变量声明 */ int result; if (num1 > num2) result = num1; else result = num2; return result; } } class Test { static void Main(string[] args) { /* 局部变量定义 */ int a = 100; int b = 200; int ret; NumberManipulator n = new NumberManipulator(); //调用 FindMax 方法 ret = n.FindMax(a, b); Console.WriteLine("最大值是: {0}", ret ); Console.ReadLine(); } } }
递归方法调用,下面是一个计算阶乘的代码,就是在自己里面调用自己。
using System; namespace CalculatorApplication { class NumberManipulator { public int factorial(int num) { /* 局部变量定义 */ int result; if (num == 1) { return 1; } else { result = factorial(num - 1) * num; return result; } } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); //调用 factorial 方法 Console.WriteLine("6 的阶乘是: {0}", n.factorial(6)); Console.WriteLine("7 的阶乘是: {0}", n.factorial(7)); Console.WriteLine("8 的阶乘是: {0}", n.factorial(8)); Console.ReadLine(); } } }
参数传递。
按值传递
只需要记住形参改变时是不会影响实参的值的,以此来保障实参的值。
按引用传递
在C#中,使用ref
关键字声明引用参数。就是共用实参的地址,不会再去创建一个新的地址。下面我们可以清晰的看到运行结果是成功交换了的。
using System; namespace CalculatorApplication { class NumberManipulator { public void swap(ref int x, ref int y) { int temp; temp = x; /* 保存 x 的值 */ x = y; /* 把 y 赋值给 x */ y = temp; /* 把 temp 赋值给 y */ } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* 局部变量定义 */ int a = 100; int b = 200; Console.WriteLine("在交换之前,a 的值: {0}", a); Console.WriteLine("在交换之前,b 的值: {0}", b); /* 调用函数来交换值 */ n.swap(ref a, ref b); Console.WriteLine("在交换之后,a 的值: {0}", a); Console.WriteLine("在交换之后,b 的值: {0}", b); Console.ReadLine(); } } }
按输出传递
基础用法与ref
一样,不过是关键字换成了out
。要记住ref
数据类型是有进有出,out
数据类型是只进不出,且out
型数据在方法中必须要赋值。
可空类型
可控类型可以理解为就是赋予一个变量的默认值为null,当然也是可以不为null的,具体用法为:int? i = 3;
,它等价于Nullable<int> i = new Nullable<int>(3);
。然后做一个对比看一下,int i; //默认值0 int? ii; //默认值null
。
上述数据类型又被称作是nullable
类型。
本文作者:信2005-2刘海涛
本文链接:https://www.cnblogs.com/lht020321/p/16755805.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步